And I updated my code like this below. But still it returns JSON :
Why?
According to your description and shared snippet I have tired to simulate your issue and its working as expected. In addition, I can switch between XML and Json response from the header value.
You can refer to following sample:
Demo Model:
public class City
{
public int Id { get; set; }
public string Name { get; set; }
}
Demo Controller:
[Route("api/[controller]")]
[ApiController]
public class CityXMLController : ControllerBase
{
public IActionResult GetCity()
{
var cityList = new List<City>()
{
new City { Id = 101, Name = "Alberta" },
new City { Id = 102, Name = "Toronto" },
new City { Id = 103, Name = "British Comlombia" },
};
return Ok(cityList);
}
}
Note: Please make sure you are using Ok as return type in order to handle dynamic request header both (XML and Json) because, specific return type would fail opposite response type as per header value.
Program.cs:
builder.Services.AddControllers(options =>
{
options.ReturnHttpNotAcceptable = true;
}).AddXmlDataContractSerializerFormatters();
Output:


Note: If you would like to know more details on Accept header configuration you could check our official document here.
Produces("application/xml")]: (annotate your controller): stackoverflow.com/a/59191378/421195[FormatFilter, Route(".../name.{format}")]