I have the following simple Web API controller:
// GET: api/customers
[HttpGet]
public async Task Get()
{
var
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.