简体   繁体   中英

How to return XML from an ASP.NET 5 MVC 6 controller action

How can I return XML from a controller action? Even when I add the header Accept: application/xml it returns a JSON object.

WebApi controllers in MVC 5 supported this. What do I have to do to make it work in MVC 6?

Microsoft removed the XML formatter, so that ASP.NET MVC 6 returns only JSON by default. If you want to add support for XML again, call AddXmlSerializerFormatters after services.AddMvc() in your Startup.ConfigureServices() method:

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

To use it, you have to add "Microsoft.AspNet.Mvc.Formatters.Xml": "6.0.0-rc1-final" as dependency (in the project.json under dependencies ).


A slightly more tedious way of doing the same thing would be to add the Xml formatter directly to the OutputFormatters collection:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc(options =>
    {
        options.OutputFormatters.Add(new XmlSerializerOutputFormatter());
    });
}

XmlSerializerOutputFormatter is in the namespace Microsoft.AspNet.Mvc.Formatters .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM