Installing Expires / Caching Headers in Web API Formatter Format

Is it possible to set expiration / caching headers inside MediaTypeFormatter in the web API? I tried to override SetDefaultContentHeaders and set the expires header as follows:

public override void SetDefaultContentHeaders(Type type, System.Net.Http.Headers.HttpContentHeaders headers, System.Net.Http.Headers.MediaTypeHeaderValue mediaType) { headers.Expires = DateTime.Now.AddHours(24); } 

But the expires header always returns with -1 when viewed in a web debugger such as Chrome tools. It also doesn't seem that setting the CacheControl header here is impossible, as it is the response header, not the content header (whatever that means).

+4
source share
2 answers

It seems that any parameter of HttpResponseMessage.Headers.CacheControl causes the Expires header to be emitted as set, but without it Expires expires with a value of -1. Try setting response.Headers.CacheControl = new CacheControlHeaderValue() , but without setting the maximum age. You should be able to do this anywhere that the HttpResponseMessage provides; e.g. in ApiController or DelegatingHandler .

According to RFC2616 , if the maximum age of CacheControl is present, it overrides Expires, but if you just set it as above, it should work.

Whether this is a good idea is controversial since Expires is HTTP 1.0 and CacheControl is HTTP 1.1.

+9
source

You must set the appropriate cache control header in the HttpResponse output object, which determines the expiration time. Unfortunately, WebAPI does not have built-in support out of the box, but, fortunately, it is not difficult to implement. See the example here: http://blog.turlov.com/2013/11/setting-cache-control-http-headers-in.html

0
source

All Articles