.Net Core MVC - cannot get 406 - Not Acceptable, always returns 200 OK with Json .Net Core MVC - cannot get 406 - Not Acceptable, always returns 200 OK with Json json json

.Net Core MVC - cannot get 406 - Not Acceptable, always returns 200 OK with Json


For ReturnHttpNotAcceptable to work, the type returned by an action must be either an ObjectResult (e.g. Ok(retval)) or a type that does not implement IActionResult (in which case the MVC framework will wrap it in an ObjectResult for you).

This is because the MVC framework only checks against the value of ReturnHttpNotAcceptable in ObjectResultExecutor, and not in any of the other IActionResultExecutor implementations (like ViewResultExecutor). (See source code for ObjectResultExecutor and ViewResultExecutor)

Put simply, make sure that the type you are returning doesn't implement (or inherit from anything that implements) IActionResult.


Add the following line in your ConfigureServices method of Startup.cs

services.AddMvcCore().AddJsonFormatters().AddApiExplorer();