Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Web Api to return XML and get XML

I have a controller which returns a data in json. I would like that method to return XML structure and get data back to XML structure.

I have added 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());
like image 917
Trupti Avatar asked Nov 20 '13 05:11

Trupti


1 Answers

To make ASP.NET Web API return XML, you don't need to make any code changes. Just ensure you have a header like this in the HTTP request.

Accept: application/xml

See this for more info on content negotiation.

like image 120
Badri Avatar answered Sep 28 '22 05:09

Badri