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.
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...
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With