ASP.NET Web Api for XML Return and XML Retrieval

I have a controller that returns data in json. I would like this method to return an XML structure and return data to an XML structure.

I added the following code to WebApiConfig:

config.Routes.MapHttpRoute( name: "defaultapi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); config.Routes.MapHttpRoute( name: "VehicleApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); config.Formatters.XmlFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/xml")); var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml"); 

Global.asax.cs

 GlobalConfiguration.Configuration.Formatters.Clear(); GlobalConfiguration.Configuration.Formatters.Add(new System.Net.Http.Formatting.XmlMediaTypeFormatter()); 
+8
c # xml asp.net-web-api asp.net-mvc-4
source share
2 answers

To force the ASP.NET Web API to return XML, you do not need to make any changes to the code. Just make sure you have such a header in your HTTP request.

 Accept: application/xml 

For more information on content negotiation, see.

+17
source share

I found that when using VBA MSXML2.XMLHTTP60 for requests, setting the request header to Accept: application / xml returns only an empty xml object. To fix this, I added the following line to the WebApiConfig.cs file at the end of the Register function:

 config.Formatters.Add(new XmlMediaTypeFormatter()); 

Then my objects were serialized as expected.

0
source share

All Articles