I have a Web API that would read XML and pass it to the appropriate model for processing.
How can I receive that XML that is coming in? Which datatype should I use?
Do I use StreamReader, StreamContent or XmlDocument or other?
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
}
}
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; }
}
This incoming XML would be deserialized to hydrate the computer parameter in the Post method.
<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
string incomingText = this.Request.Content.ReadAsStringAsync().Result;
XElement incomingXml = XElement.Parse(incomingText);
XElement.Attribute("name").Value. As for nested nodes, those would be represented in the model as object properties.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();
}