12

我有一个 Web API 可以读取 XML 并将其传递给适当的模型进行处理。

我怎样才能接收进来的 XML?我应该使用哪种数据类型?

我使用StreamReader,StreamContent还是XmlDocument其他?

4

2 回答 2

16

ASP.NET Web API 使用内容协商将传入的 http 请求自动反序列化为模型类。开箱即用,这将适用于任何 XML、JSON 或 wwww-form-urlencoded 消息。

public class ComputerController : ApiController
{
    public void Post(ComputerInfo computer)
    {
        // use computer argument
    }
}

创建一个映射到 XML 属性的模型类。

public class ComputerInfo
{
    public string Processor { get; set; }
    public string HardDrive { get; set; }
}

这个传入的 XML 将被反序列化以在 Post 方法中水合计算机参数。

<ComputerInfo>
   <Processor>AMD</Processor>
   <HardDrive>Toshiba</HardDrive>
</ComputerInfo>

如果出于某种原因您想手动读取和解析传入的 xml,您可以这样做

string incomingText = this.Request.Content.ReadAsStringAsync().Result;
XElement incomingXml = XElement.Parse(incomingText);
于 2013-09-04T07:13:54.713 回答
5

任何传入的内容都可以作为字节流读取,然后根据需要进行处理。

public async Task<HttpResponseMessage> Get() {

   var stream = await Request.Content.ReadAsStreamAsync();

   var xmlDocument = new XmlDocument();
   xmlDocument.Load(stream);

   // Process XML document

   return new HttpResponseMessage();
}
于 2013-09-04T12:25:34.877 回答