C# 如何从 ASP.NET Web API 读取 XML?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18607381/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 12:43:05  来源:igfitidea点击:

How to read XML from ASP.NET Web API?

c#asp.net-web-api

提问by NotMe

I have a Web API that would read XML and pass it to the appropriate model for processing.

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

How can I receive that XML that is coming in? Which datatype should I use?

我怎样才能收到传入的 XML?我应该使用哪种数据类型?

Do I use StreamReader, StreamContentor XmlDocumentor other?

什么时候使用StreamReaderStreamContent或者XmlDocument还是其他?

采纳答案by Despertar

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.

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

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


Create a model class which maps to the properties of the XML.

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

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


This incoming XML would be deserialized to hydrate the computer parameter in the Post method.

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

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


If for whatever reason you want to manually read and parse the incoming xml, you can do so like this

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

string incomingText = this.Request.Content.ReadAsStringAsync().Result;
XElement incomingXml = XElement.Parse(incomingText);

回答by Darrel Miller

Any incoming content can be read as a stream of bytes and then processed as required.

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

public async Task<HttpResponseMessage> Get() {

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

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

   // Process XML document

   return new HttpResponseMessage();
}