Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have the following simple Web API controller:

    // GET: api/customers
    [HttpGet]
    public async Task<IActionResult> Get()
        {
        var customers = await uow.Users.GetAllAsync();
        var dto = customers.Select(p => new CustomerDto {Id = p.Id, Email = p.Email, UserName = p.UserName});
        return Ok(dto); // IEnumerable<CustomerDto>
        }

In Postman, I'm setting the Accept header to application/xml, but no matter what I try, I can only get JSON data back.

Postman screen shot

I read somewhere that in order to get XML, I must add [DataContract] and [DataMember] attributes to my DTO, which now looks like this:

[DataContract]
public class CustomerDto
    {
    [DataMember]
    public string Id { get; set; }

    [Required]
    [EmailAddress]
    [Display(Name = "Email")]
    [DataMember]
    public string Email { get; set; }

    [Required]
    [Display(Name = "Login Name")]
    [DataMember]
    public string UserName { get; set; }
    }

I've been at it several hours now and I'm just not seeing why it doesn't work. I've tried:

  • Making the action method synchronous and asynchronous

  • Returning the data directly, and setting the return type to IEnumerable<CustomerDto>

  • Converting the collection to an array instead of a list

  • Returning an IActionResult

  • Returning a single item, instead of a collection

  • I've verified that the Accept header is showing up in the request by examining it in the debugger.

  • Lots of "Googling with Bing" and reading various blogs

  • Creating a new WebAPI project from the template and seeing if there is any inspiration there (not really).

    I expect it's simple, but I can't see it...

like image 277
Tim Long Avatar asked Sep 05 '25 03:09

Tim Long


1 Answers

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();
like image 50
Kiran Avatar answered Sep 07 '25 21:09

Kiran