For example, I request "text/xml" and I receive an answer in Xml format? I found that there is an OutputFormatters, but I do not quite understand how to work with it. Also, apparently, the [Produces] attribute is somehow connected with this, but it also raises questions

1 answer 1

In the old ASP.NET Web API (non-Core), two formatters are already connected, for XML and for JSON.

In the Web API Core, by default there is only JSON, the XML formatter must be connected additionally. To do this, add the Microsoft.AspNetCore.Mvc.Formatters.Xml package to the project.json file (in the dependencies section):

 "Microsoft.AspNetCore.Mvc.Formatters.Xml": "1.0.1-*" 

Then in the startup class in the ConfigureServices method, call AddXmlSerializerFormatters :

 public void ConfigureServices(IServiceCollection services) { services.AddMvc().AddXmlSerializerFormatters(); } 

Now you can specify the required data format in the Accept header of the request to the controller (if no header is specified, JSON is returned):

 var request = new XMLHttpRequest(); request.open('GET', '/api/test'); request.setRequestHeader('Accept', 'text/xml'); request.onreadystatechange = function() { if (request.readyState == 4 && request.status == 200) { console.log(request.responseXML); } }; request.send(); 

Or, if you use jQuery, you need to set the dataType parameter to 'xml' :

 $.ajax({ url: '/api/test', dataType: 'xml' }).then(function (data) { console.log(data); }); 
  • Maybe you still clarify when using InputFormatters ? - Qutrix
  • @Qutrix wrote in the answer to your second question on FromBody - kmv