如何从ASP.NET Web API读取XML? [英] How to read XML from ASP.NET Web API?
问题描述
我有一个Web API,可以读取XML并将其传递给适当的模型进行处理.
I have a Web API that would read XML and pass it to the appropriate model for processing.
如何接收即将到来的XML?我应该使用哪种数据类型?
How can I receive that XML that is coming in? Which datatype should I use?
我是否使用 StreamReader
, StreamContent
或 XmlDocument
或其他?
Do I use StreamReader
, StreamContent
or XmlDocument
or other?
推荐答案
ASP.NET Web API使用内容协商将输入的HTTP请求自动反序列化为模型类.开箱即用,它将与任何XML,JSON或wwww-form-urlencoded消息一起使用.
ASP.NET Web API uses content negotiation to automatically deserialize an incoming http request into a model class. Out of the box, this this will work with any XML, JSON, or wwww-form-urlencoded message.
public class ComputerController : ApiController
{
public void Post(ComputerInfo computer)
{
// use computer argument
}
}
创建一个映射到XML属性的模型类.
Create a model class which maps to the properties of the XML.
public class ComputerInfo
{
public string Processor { get; set; }
public string HardDrive { get; set; }
}
此传入的XML将反序列化以在Post方法中混合计算机参数.
This incoming XML would be deserialized to hydrate the computer parameter in the Post method.
<ComputerInfo>
<Processor>AMD</Processor>
<HardDrive>Toshiba</HardDrive>
</ComputerInfo>
如果出于任何原因要手动读取和解析传入的xml,都可以这样做
If for whatever reason you want to manually read and parse the incoming xml, you can do so like this
string incomingText = this.Request.Content.ReadAsStringAsync().Result;
XElement incomingXml = XElement.Parse(incomingText);
这篇关于如何从ASP.NET Web API读取XML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!