Uriil
Uriil

Reputation: 12628

Extending MediaTypeFormatter selection

In some cases i want to select MediaTypeFormatter manually. Is there any way to do this?

For example if User Agent is Opera, always return data in JSON format

Upvotes: 0

Views: 416

Answers (1)

Kiran
Kiran

Reputation: 57969

Sure, you could create a custom MediaTypeMapping and add into the formatters.

Example below:

config.Formatters.JsonFormatter.MediaTypeMappings.Add(new UserAgentMediaTypeMapping("Chrome", "application/json"));

-----------------------------------------------------

public class UserAgentMediaTypeMapping : MediaTypeMapping
{
    private string _userAgent;

    public UserAgentMediaTypeMapping(string userAgent, string mediaType)
        : base(mediaType)
    {
        //todo: error check

        _userAgent = userAgent.ToLowerInvariant();
    }

    public UserAgentMediaTypeMapping(string userAgent, MediaTypeHeaderValue mediaType)
        : base(mediaType)
    {
        //todo: error check

        _userAgent = userAgent.ToLowerInvariant();
    }

    public string UserAgent 
    {
        get
        {
            return _userAgent;
        }
    }

    public override double TryMatchMediaType(HttpRequestMessage request)
    {
        HttpHeaderValueCollection<ProductInfoHeaderValue> agents = request.Headers.UserAgent;

        foreach (ProductInfoHeaderValue pihv in agents)
        {
            if (pihv.Product != null)
            {
                if (pihv.Product.Name.ToLowerInvariant() == UserAgent)
                {
                    return 1.0;
                }
            }
        }

        return 0.0;
    }
}

More info from my old blog posts(1, 2) related to con-neg:

What happens when multiple formatters match an incoming request’s criteria? Which one does the Conneg algorithm choose?

During the Conneg algorithm run, based on bunch of criteria like the Request Accept header, Content-Type header, MediaTypeMapping etc, there is always a possibility that more than one formatter could indicate its availability in writing the Response. As you can imagine, the Conneg algorithm has to choose only one formatter in the end. The Default Conneg algorithm has the following precedence order to select the final formatter:

  1. Formatter match based on Media Type Mapping.
  2. Formatter match based on Request Accept header's media type.
  3. Formatter match based on Request Content-Type header's media type.
  4. Formatter match based on if it can serialize the response data’s Type.

Upvotes: 1

Related Questions