12

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?

2 Answers 2

17

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);
Sign up to request clarification or add additional context in comments.

9 Comments

Using ReadAsStreamAsync and Load is a better option than ReadAsString and Parse.
@DarrelMiller Why is that?
Because ReadAsString may choose a different string encoding than is defined in the XML doc.
@Despertar Thanks. It works. I just have 2 more questions to ask, how do we handle attributes and nested nodes?
Attributes do not play well with the default serialization. If you were to take an object an serialize it into XML you will notice it will not create attributes (except for namespaces). You would probably need to use the last technique to manually pull attribute values XElement.Attribute("name").Value. As for nested nodes, those would be represented in the model as object properties.
|
5

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();
}

1 Comment

"a stream of bytes" - for some reason this makes me think of a piranha-infested portion of the Orinoco. More seriously, though, I've posted a related question at stackoverflow.com/questions/21994108/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.