Statuscode 406 (Not Acceptable) in ASP.NET Core

I had this before:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
}

Then I change it to AddMvcCore() instead of AddMvc()

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvcCore();
}

Finally I had that issue with the Response 406 so what I did was to add .AddJsonFormatters() to services.AddMVCCore() and my API worked again.

public void ConfigureServices(IServiceCollection services)
{
   services.AddMvcCore()
        .AddJsonFormatters();
}

In such cases, it’s a good idea to find the commit that removed the functionality, to see what it likely got replaced with. In this case, HttpNotAcceptableOutputFormatter was removed with this commit to fix issue #4612:

Alter content negotiation algorithm so that it can be configured (via MvcOptions) to always respect an explicit Accept header.

What it was replaced with is MvcOptions.ReturnHttpNotAcceptable, which is a setting on the MvcOptions that you configure when adding MVC with AddMvc.

So your code should become like this:

services.AddMvc(options =>
{
    options.ReturnHttpNotAcceptable = true;
});

You add this to the ConfigureService method in the Startup class.

services.AddMvc(options =>
{
    options.ReturnHttpNotAcceptable = true;
    // If you need to add support for XML
    // options.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter());
});

Tags:

Asp.Net Core