Search code examples
asp.netjsonxmlasp.net-core

Default Accept Media Type on ASP.NET controller


I have a controller that currently only return data formatted as XML that look like this:

[Produces(MediaTypeNames.Application.Xml)]
public class MyController  { /* implementation details */}

I want to add the possibility of returning data formated as JSON so I added the JSON media type to the ProducesAttribute like that

[Produces(MediaTypeNames.Application.Xml, MediaTypeNames.Application.Json)]
public class MyController  { /* implementation details */}

It works as expected when the HTTP request has the correct Accept Header. But when the HTTP request has no Accept header, the controller now respond in JSON whereas it responded in XML before.

Is there a way to define the default Media type response on a controller that support multiple media type formats ?

I've tried to different parameter orders in the attribute constructor but it didn't change anything


Solution

  • If the client request doesn't specify any Accept header or if it uses */* meaning any content type is acceptable, ASP.NET Core will use JSON as the default response format, as JSON is the more commonly used format in modern web APIs.

    To change the default format, you could use the output formatter:

    var builder = WebApplication.CreateBuilder(args);
        
    builder.Services.AddControllers()
                    .AddXmlSerializerFormatters()
                    .AddMvcOptions(options =>
                    {
                        var xmlFormatter = options.OutputFormatters.OfType<XmlSerializerOutputFormatter>().First();
                        options.OutputFormatters.Remove(xmlFormatter);
                        options.OutputFormatters.Insert(0, xmlFormatter);
                    }); 
        
    var app = builder.Build();
    // ...rest of your configuration
    

    Here is the official document which can give you more information:

    Format response data in ASP.NET Core Web API