Luke Puplett
Luke Puplett

Reputation: 45253

WebAPI 2 - Custom content types and negotiation

Really simple question but I can't find a simple example in the docs, or whether it'll just work.

I want to version one of my API resources. I want to add application/vnd.myEntityV2+json and ...+xml as custom content types, then check the Accept header in my controller and call the appropriate code. Simple idea.

Will the built-in WebAPI content negotiation see the +json|+xml on the end and pick the right formatter?

Or do I need to configure two mappings, or something else completely?

Upvotes: 0

Views: 351

Answers (1)

Luke Puplett
Luke Puplett

Reputation: 45253

Here's what I've done:

JsonMediaTypeFormatter jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().Single();
jsonFormatter.MediaTypeMappings.Add(
    new RequestHeaderMapping(HttpRequestHeaders.Accept, "+json", StringComparison.OrdinalIgnoreCase, true, new MediaTypeHeaderValue(MimeTypes.ApplicationJson)));

Note HttpRequestHeaders and MimeTypes are my own types.

That should catch any content-type containing +json.

Upvotes: 1

Related Questions