Range implementation and MediaTyeFormatter

Topics: ASP.NET Web API, General
Jul 30, 2012 at 3:40 PM


I have been looking into custom Range implementation and abstracting it away in a reusable module.

For a lot of cases it makes sense to implement this in MediaTypeFormatter. ContentRange header sits on Content headers, so MediaTypeFormatter has access to it.

But MediaTypeFormatter does not have access to the request and its headers so it cannot find out about the Range header.

I appreciate that it is best to limit access of various parts of the system to the bits they do not need (access to the whole request is definitely not good in a mediatypeformatter) but I believe access to request headers (and in this case Range header) is useful and sometimes required.

So how do you see that working?


Jul 30, 2012 at 3:53 PM
Edited Jul 30, 2012 at 4:05 PM

I take back what I said until I can verify it.

Jul 30, 2012 at 4:39 PM

Thanks Glenn. I could only find GetPerRequestFormatterInstance which does not seem to be useful.

Jul 30, 2012 at 4:42 PM

Yeah I think I was mistaken. I thought I remember we added a method like that, but I guess not.

One trick you could do (but it's ugly) is to add a custom header on the content headers which you set via a message handler or a filter.

Jul 30, 2012 at 4:47 PM
Edited Jul 30, 2012 at 4:48 PM

It is funny because I thought about it and as a hack was happy to do and wanted to do it in my RangeDelegatingHandler. Problem is delegating handler does not have access to response headers (and response content headers) until it is already late and MediaTypeFormatter has finished its formatting job. So no avail there ....

Jul 30, 2012 at 4:55 PM

Another option might be to use ConditionalWeakTable adding the HttpContent class as the key and the request being the value. You could then have an extension method off of the HttpContent that retrieves the request. You basically would populate the table in a message handler/filter. ConditionalWeakTable doesn't keep things alive as it uses weak references, and the GC automatically cleans it out.


Jul 30, 2012 at 5:01 PM

What about using a filter?

Jul 30, 2012 at 5:32 PM
GetPerRequestFormatterInstance was designed for precisely this scenario.

You implement this method, and return a new instance of the formatter that has captured the request object, so that it will be available to you throughout the lifetime of the request.
Jul 30, 2012 at 9:00 PM

Alright, so it is the same method Glenn was talking about! Usage was not immediately clear but it makes sense now that you explain.

I am also warming up to the idea of filters. I suppose you have everything you need in there. Will review options and will be blogging about it.

Jul 31, 2012 at 10:24 PM

Finally used Filters: http://byterot.blogspot.co.uk/2012/07/range-header-asp-net-web-api-entity-pagination.html