Why my API is returning JSON format on Header "accept: application/xml"?

Ken Martos 36 Reputation points
2022-06-03T18:25:42.557+00:00

I'm building an API with OData integration returning response JSON and XML format, but why is my API returning JSON format instead of XML format on the header accept: application/xml

This is my Program.cs with Odata and XML formatter.

using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.AspNetCore.OData;

var builder = WebApplication.CreateBuilder(args);

...

builder.Services.AddControllers()
    .AddOData(options => options.Select().Filter().OrderBy().Expand().OrderBy().Count());

builder.Services.AddMvc(options =>
{
    options.RespectBrowserAcceptHeader = true;
    options.ReturnHttpNotAcceptable = true;
    options.OutputFormatters.Add(new XmlSerializerOutputFormatter());
});

And this is the controller I've been testing on.

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.OData.Formatter;
using Microsoft.AspNetCore.OData.Query;
using Microsoft.AspNetCore.OData.Routing.Controllers;

namespace OData.Controllers
{
    [Produces("application/json", "application/xml")]
    [ApiController]
    [Route("[controller]")]
    [FormatFilter]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }

        [HttpGet(Name = "GetWeatherForecast")]
        [EnableQuery]
        [FormatFilter]
        public IActionResult Get()
        {
            return Ok(Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)]
            })
            .ToArray());
        }
    }
}

what seems to be the problem?

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,184 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 56,686 Reputation points
    2022-06-04T15:23:18.57+00:00

    Xml is not really supported. See this issue thread.

    https://github.com/OData/WebApi/issues/2330