Why won't my ASP.Net Core Web API Controller return XML?

Xml formatters are part of a separate package: Microsoft.AspNetCore.Mvc.Formatters.Xml

Add the above package and update your startup.cs like below:

services
    .AddMvc()
    .AddXmlDataContractSerializerFormatters();

OR

services
    .AddMvc()
    .AddXmlSerializerFormatters();

For Asp.Net Core 2.x you basically need these 3 things in order to return an XML response:

Startup.cs:

services
    .AddMvcCore(options => options.OutputFormatters.Add(new XmlSerializerOutputFormatter())

CustomerController.cs:

using Microsoft.AspNetCore.Mvc;

namespace WebApplication
{
    [Route("api/[controller]")]
    public class CustomerController : ControllerBase
    {
        [HttpGet]
        public IActionResult Get()
        {
            var customer = new CustomerDto {Id = 1, Name = "John", Age = 45};
            return Ok(customer);
        }
    }
}

CustomerDto.cs:

namespace WebApplication
{
    public class CustomerDto
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
    }
}

And then upon adding the Accept "application/xml" header to the request an XML formatted result will be returned.

A very important note that I had to find out for myself is if your model does not have an implicit of explicit parameterless constructor then the response will be written as a json. Given the following example

namespace WebApplication
{
    public class CustomerDto
    {
        public CustomerDto(int id, string name, int age)
        {
            Id = id;
            Name = name;
            Age = age;
        }

         public int Id { get; }
         public string Name { get; }
         public int Age { get; }
    }
}

It would return json. To this model you should add

public CustomerDto()
{
}

And that would again return XML.


For asp.net core 2.x, you can configure OutputFormatter.

you can try following code pieces in startup.cs class ConfigureServices method.

public void ConfigureServices(IServiceCollection services)
{
     services.AddMvc(action =>
     {
         action.ReturnHttpNotAcceptable = true;
         action.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter());
     });

     //...
}

For using XmlDataContractSerializerOutputFormatter references from Microsoft.AspNetCore.Mvc.Formatters package from nuget.

now it should work for xml and json