3

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?

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

8 Comments

What class does MvcOptions come from?
@Nulref It's in the namespace Microsoft.AspNet.Mvc
It's now Microsoft.AspNet.Mvc.Formatters.Xml not Microsoft.AspNet.Mvc.Xml
I've updated the answer to reflect the current usage, including the namespace change.
@JimmyBoh thanks, I've edited the question myself, since your edit was rejected.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.