2

If one omits the Accept header in a request to an Asp.Net web API the server will return (415) Unsupported Media Type

I am looking for a way to force the API to assume a default return type (in my case, application/json) when the request does not contain an Accept value in its headers.

After a substantial amount of reading and searching, I'm not sure this is even possible?

Jimbo
  • 22,379
  • 42
  • 117
  • 159

2 Answers2

2

You can force the framework to use XML formatter when HTTP Accept header is missing, by doing the following trick:

var jsonFormatter = config.Formatters.JsonFormatter;
config.Formatters.Remove(config.Formatters.JsonFormatter);
config.Formatters.Add(jsonFormatter);

This way the JSON formatter will be the second registered formatter in the list, and the XML will be the first one.

Vasile Pojoga
  • 31
  • 1
  • 5
1

This is content negotiator resposibility to choose the right formatter to serialize the response object. But by default WebApi framework gets JsonFormatter if could not find appropriate formatter.

If there are still no matches, the content negotiator simply picks the first formatter that can serialize the type.

So it is strange behavior. Anyway you could set up custom content negotiator to choose explicit JsonFormatter if request does not have Accept header.

public class JsonContentNegotiator : DefaultContentNegotiator
{
    protected override MediaTypeFormatterMatch MatchAcceptHeader(IEnumerable<MediaTypeWithQualityHeaderValue> sortedAcceptValues, MediaTypeFormatter formatter)
    {
        var defaultMatch = base.MatchAcceptHeader(sortedAcceptValues, formatter);

        if (defaultMatch == null)
        {
            //Check to find json formatter
            var jsonMediaType = formatter.SupportedMediaTypes.FirstOrDefault(h => h.MediaType == "application/json");
            if (jsonMediaType != null)
            {
                return new MediaTypeFormatterMatch(formatter, jsonMediaType, 1.0, MediaTypeFormatterMatchRanking.MatchOnRequestAcceptHeaderLiteral);
            }
        }

        return defaultMatch;
    }
}

And replace in HttpConfiguration object

config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator());
Ivan R.
  • 1,875
  • 1
  • 13
  • 11