7

I am trying to implement CacheControl headers from within a ASP.NET Web Api action ( I realise I can do this using other libraries, and in filters/handlers, but want to do some testing first).

I am following a trivial example from a book that looks like:

var response = Request.CreateResponse<IEnumerable<string>>(HttpStatusCode.OK,emails);

response.Headers.CacheControl = new CacheControlHeaderValue();
response.Headers.CacheControl.MaxAge = TimeSpan.FromHours(1);
response.Headers.CacheControl.MustRevalidate = false;
response.Headers.CacheControl.Public = true;

return response;

This code is almost identical to a number of other answers provided on stackoverflow.

However, the web api is not setting cache control header at all! Any ideas?????

When I look at the response in fiddler it looks like the following, as you can the cache-control is set to no-cache.

HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
X-MiniProfiler-Ids: ["b7bfde10-e8d3-455d-b40d-2f33eb285023"]
X-Powered-By: ASP.NET
Date: Sat, 25 May 2013 11:54:35 GMT
Content-Length: 24

I have tried changing the maxage, mustrevalidate and public values all to no avail...

  • 1
    I just check your response code... working for me. It seems that the issue is elsewhere...in your solution *(some AOP filter?, attribute?)* – Radim Köhler May 25 '13 at 13:40
  • 1
    I agree with Radim, your code is fine. Do you have any MessageHandlers installed? – Darrel Miller May 25 '13 at 13:41
  • 1
    Did you ever find the reason for this not working? I am running into the same issue trying to integrate webapi into a legacy MVC project. – Chad May 22 '14 at 15:11
  • 1
    I have the same issue, using [EnableCors(origins: "*", headers: "*", methods: "*")] header on the API action. Wonder if this could cause the problem. – gbro3n Jul 23 '15 at 10:04

1 Answers1

3

Check your request pipeline to see if you have something that is manipulating your response via the System.Web.HttpResponse object (ex: HttpContext.Current.Response). I've run into cases where adding http cookies via System.Web.HttpResponse will wipe out any cache-control headers defined within Web API's System.Net.Http.HttpResponseMessage.

Try avoiding System.Web.HttpResponse. If that's not possible, one workaround as discussed here would be to manually set the cookie header via AddHeader() and avoid the Cookies collection altogether.

Community
  • 1
  • 1
Ryan Tofteland
  • 913
  • 6
  • 11