WebAPI to Return XML
Here's another way to be compatible with an IHttpActionResult return type. In this case I am asking it to use the XML Serializer(optional) instead of Data Contract serializer, I'm using return ResponseMessage(
so that I get a return compatible with IHttpActionResult:
return ResponseMessage(new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ObjectContent<SomeType>(objectToSerialize,
new System.Net.Http.Formatting.XmlMediaTypeFormatter {
UseXmlSerializer = true
})
});
If you don't want the controller to decide the return object type, you should set your method return type as System.Net.Http.HttpResponseMessage
and use the below code to return the XML.
public HttpResponseMessage Authenticate()
{
//process the request
.........
string XML="<note><body>Message content</body></note>";
return new HttpResponseMessage()
{
Content = new StringContent(XML, Encoding.UTF8, "application/xml")
};
}
This is the quickest way to always return XML from Web API.
If you return a serializable object, WebAPI will automatically send JSON or XML based on the Accept header that your client sends.
If you return a string, you'll get a string.