Web-based Route Formatting Configuration

The name more or less speaks of everything. I am trying to configure the JSON MediaTypeFormatter to behave differently in each route.

In particular, I have two routes in my WebAPI that are mapped to the same controller. Each route performs the same operation and returns the same data, but for reasons of backward compatibility with existing consumers, they should format their result in a slightly different way.

I could put some code in the controller to determine if the request came to an obsolete route or a new route, and change the formatters accordingly.

I could also use ActionFilter to change the formats where necessary.

I was wondering if there is a way to configure formatter at the route level, because this is the abstraction layer, where my API behaves differently. This can be either at the route configuration point or in the delegate handler.

Any suggestions?

+6
source share
1 answer

I'm not quite sure how much your two JSONs differ and what you do with them, but if you ask me, I will do this in the format:

public class MyJsonMediaTypeFormatter : JsonMediaTypeFormatter { private IHttpRouteData _route; public override MediaTypeFormatter GetPerRequestFormatterInstance(Type type, HttpRequestMessage request, System.Net.Http.Headers.MediaTypeHeaderValue mediaType) { _route = request.GetRouteData(); return base.GetPerRequestFormatterInstance(type, request, mediaType); } public override System.Threading.Tasks.Task WriteToStreamAsync(Type type, object value, System.IO.Stream writeStream, HttpContent content, TransportContext transportContext) { if (_route.Route.RouteTemplate.Contains("legacy")) { //here set the SerializerSettings for non standard JSON //I just added NullValueHandling as an example this.SerializerSettings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }; } return base.WriteToStreamAsync(type, value, writeStream, content, transportContext); } } 

Then you replace the default JsonMEdiaTypeFormatter with this.

  config.Formatters.RemoveAt(0); config.Formatters.Insert(0, new MyJsonMediaTypeFormatter()); 

In the web API, you can have a DelegatingHandler that only works on a specific route, but that doesn't make sense, since the Formatters collection is global, so it makes no sense to change this at runtime even from a route, area handler.

+6
source

All Articles