Eric Lundmark
Eric Lundmark

Reputation: 229

SupportedMediaTypes not used when doing content negotiation

I have created a new formatter in order to handle content negotiation.

public TiffImageFormatter()
{
    SupportedMediaTypes.Add(new MediaTypeHeaderValue("image/tiff"));
}

public override bool CanReadType(Type type)
{
    return type == typeof(byte[]);
}

public override bool CanWriteType(Type type)
{
    return type == typeof(byte[]);
}

But when running

var negotiator = Configuration.Services.GetContentNegotiator();
var type = negotiator.Negotiate(typeof(byte[]), Request, Configuration.Formatters);

The supported media types are not taken into consideration instead "CanWritetype" is the only condition determining what accept type to use.

Accept: image/*, image/png, image/tiff, */* should result in image/tiff but Accept: image/png should return in null allowing me to send not acceptable.

How can I determine which is the correct media type?

Upvotes: 2

Views: 608

Answers (1)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149618

You need to use MediaTypeFormatter.MediaTypeMappings and add the relevant Accept headers:

public TiffImageFormatter()
{
    SupportedMediaTypes.Add(new MediaTypeHeaderValue("image/tiff"));
    MediaTypeMappings.Add(
                new RequestHeaderMapping("Accept", "image\tiff", 
                                          StringComparison.OrdinalIgnoreCase,
                                          false, "image\tiff"));
}

This blog post explains the algorithm for media type matching if you need any further information.

Upvotes: 1

Related Questions