8

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());
Taylan Aydinli
  • 4,333
  • 15
  • 39
  • 33
Trupti
  • 597
  • 4
  • 8
  • 17
  • Possible duplicate of [How to return Xml Data from a Web API Method?](https://stackoverflow.com/questions/15366096/how-to-return-xml-data-from-a-web-api-method) – Clint Jul 07 '17 at 13:43

3 Answers3

18

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.

  • Where to add Accept: application/xml – Trupti Nov 20 '13 at 07:12
  • also let me know where do i have to create XML structure and respected xslt file, i am doing web api in ASP.NET MVC4 – Trupti Nov 20 '13 at 07:13
  • 2
    `Accept: application/xml` should to to your request headers. Web API will automatically return XML. Here is a good post if you want to return only one format http://www.strathweb.com/2013/06/supporting-only-json-in-asp-net-web-api-the-right-way/ – Nikolai Samteladze Nov 20 '13 at 15:08
0

I found when using VBA MSXML2.XMLHTTP60 to make requests, setting the request header to Accept: application/xml would only return a blank xml object. To fix this, I added the following line to my WebApiConfig.cs file at the end of the Register function:

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

Then my objects were serialized as expected.

akerra
  • 1,017
  • 8
  • 18
0

Make sure that your return type is serializable.

cimey
  • 189
  • 3
  • 10