Skip to content

Content Negotiation via an Accept header #212

@partomatl

Description

@partomatl

Hi all,
I am trying to use both JSON and MessagePack formats in an API endpoint.

I added the MessagePack formatters to MVC's configuration (in Startup.cs):

services.AddMvc().AddMvcOptions(option =>
            {
                option.OutputFormatters.Add(new MessagePackOutputFormatter(StandardResolver.Instance));
                option.InputFormatters.Add(new MessagePackInputFormatter(StandardResolver.Instance));
            });

According to https://docs.microsoft.com/en-us/aspnet/core/mvc/models/formatting,

Content negotiation only takes place if an Accept header appears in the request. When a request contains an accept header, the framework will enumerate the media types in the accept header in preference order and will try to find a formatter that can produce a response in one of the formats specified by the accept header. In case no formatter is found that can satisfy the client's request, the framework will try to find the first formatter that can produce a response (unless the developer has configured the option on MvcOptions to return 406 Not Acceptable instead). If the request specifies XML, but the XML formatter has not been configured, then the JSON formatter will be used. More generally, if no formatter is configured that can provide the requested format, then the first formatter that can format the object is used. If no header is given, the first formatter that can handle the object to be returned will be used to serialize the response. In this case, there isn't any negotiation taking place - the server is determining what format it will use.

But the framework does not seem to care about the Accept header I am sending.
When both JSON and MessagePack formatters are in the MVC's configuration, the API gives a application/json response even when I am sending a request with a Accept: application/x-msgpack header.

A workaround is to use the [Produces] filter for the controllers which should produce application/x-msgpack responses:

[Produces("application/x-msgpack")]
public class SearchController { ... }

However, it would be more convenient to be able to specify the preferred response format at the request level by specifying the Accept header.

Is this the normal behavior or am I missing something here?
Thank you!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions