'Statuscode 406 (Not Acceptable) in ASP.NET Core

REST services should provide content negotiation. This means that clients send an Accept header that contains the desired content type of the response. If the service does not support this media type, it should respond with status code 406 (Not Acceptable).

I try to map this behavior to ASP.NET Core. ASP.NET core returns a JSON document, if it doesn't recognize the media type in the Accept header. In previous versions of the framework the behavior described above could be achieved by adding a special output formatter to the configuration:

public void ConfigureServices(IServiceCollection services) {
  services.AddMvc(options => {
    options.OutputFormatters.Insert(0, new HttpNotAcceptableOutputFormatter());
  });
}

Unfortunately, HttpNotAcceptableOutputFormatter was removed from the ASP.NET Core framework after RC1. Is there any replacement for this class in the current version of the framework?



Solution 1:[1]

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();
}

Solution 2:[2]

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());
});

Solution 3:[3]

None of the above answer worked for me , finally this worked

Adding the following line in ConfigureServices of Startup.cs

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 glennsl
Solution 2 R. Richards
Solution 3 Musab