Search code examples
asp.net-coreapi-versioning

How to get MvcOptions.ReturnHttpNotAcceptable to work together with ApiVersioning


I'd like to return HTTP 406 if the version requested is not supported. So I have:

services.AddApiVersioning(options =>
{
   options.ReportApiVersions = true;
   options.AssumeDefaultVersionWhenUnspecified = false;
   options.ApiVersionReader = new MediaTypeApiVersionReader();
});
services.AddMvc(options =>
{
   options.RespectBrowserAcceptHeader = true;
   options.ReturnHttpNotAcceptable = true;  // Return HTTP 406
});

But this always returns HTTP 406 even if the version is correct (e.g. application/json;v=1.0 or application\vnd.acme+json;v=1).

If I set ReturnHttpNotAcceptable to false, I get HTTP 400 (Bad Request) when version is unsupported, and HTTP 200 if version is supported.

Also, if I set my ApiVersionReader to be HeaderApiVersionReader, and set ReturnHttpNotAcceptable to true, it returns an HTTP 400 instead of 406 when the version is unsupported.

If I disable versioning altogether, I get HTTP 406 correctly with ReturnHttpNotAcceptable set to true and if, say, the request has appliction/xml and the API does not support XML.

I've asked this question on ASP.NET API Versioning on Github, but I'm wondering if this is just something I have not figured out, and could get an answer from this forum.


Solution

  • As indicated in the discussion here, I ended up with this approach:

    • I created an output formatter that accepts media type with version parameter (e.g. application/json;version=1.0 or application/vnd.acme+json;version=1.0)
    • I created a subsclass of ApiVersioning's DefaultErrorResponseProvider so it returns a HTTP 406 when the version specified in the Accept header is not accepted.