asp.net-mvc – ASP.NET MVC Web API缓存控制头部没有发送响应,尽管配置在响应对象上

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – ASP.NET MVC Web API缓存控制头部没有发送响应,尽管配置在响应对象上前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图在ASP.NET MVC Web API中设置缓存头,但IIS的响应表明CacheControl值被忽略.

我原来的假设是我在System.Web.Http.Cors中使用了EnableCorsAttribute,这在这个用例中是必需的.然而,即使没有该属性,响应Cache-Control头仍然是“私有”.

有没有什么我在这里做错了?

  1. // GET api/<version>/content
  2. // [EnableCors(origins: "*",headers: "*",methods: "*")]
  3. public HttpResponseMessage Get(HttpRequestMessage request)
  4. {
  5. int cacheMaxAgeSeconds;
  6.  
  7. string cacheMaxAgeString = request.GetQueryString("cache-max-age") ?? request.GetQueryString("cache-max-age-seconds");
  8.  
  9. string rawUri = request.RequestUri.ToString();
  10.  
  11. try
  12. {
  13. cacheMaxAgeSeconds = cacheMaxAgeString == null ? Config.ApiCacheControlMaxSeconds : int.Parse(cacheMaxAgeString);
  14. }
  15. catch (Exception ex)
  16. {
  17. cacheMaxAgeSeconds = Config.ApiCacheControlMaxSeconds;
  18.  
  19. //...
  20. }
  21.  
  22. try
  23. {
  24. //...
  25.  
  26. var response = new HttpResponseMessage(HttpStatusCode.OK)
  27. {
  28. Content = new StringContent("...",Encoding.UTF8,"application/json")
  29. };
  30.  
  31. response.Headers.CacheControl = new CacheControlHeaderValue
  32. {
  33. Public = true,MaxAge = TimeSpan.FromSeconds(cacheMaxAgeSeconds)
  34. };
  35.  
  36. return response;
  37. }
  38. catch (Exception apiEx)
  39. {
  40. //...
  41. }
  42. }

响应

  1. HTTP/1.1 200 OK
  2. Cache-Control: private
  3. Content-Type: application/json; charset=utf-8
  4. Date: Thu,23 Jul 2015 10:53:17 GMT
  5. Server: Microsoft-IIS/7.5
  6. Set-Cookie: ASP.NET_SessionId=knjh4pncbrhad30kjykvwxyz; path=/; HttpOnly
  7. X-AspNet-Version: 4.0.30319
  8. X-Powered-By: ASP.NET
  9. Content-Length: 2367
  10. Connection: keep-alive

解决方法

以下代码在vanilla WebApi应用程序(System.Web.Http 4.0.0.0)中正确设置“cache-control:public,max-age = 15”.所以…它可能不是WebApi本身导致的问题.

您的项目中可能会有一些魔法改变缓存设置(想到全局动作过滤器或类似的东西).或者也许你正在通过代理重写HTTP头.

  1. public HttpResponseMessage Get()
  2. {
  3. var content = new JavaScriptSerializer().Serialize(new { foo = "bar" });
  4.  
  5. var response = new HttpResponseMessage(HttpStatusCode.OK)
  6. {
  7. Content = new StringContent(content,"application/json")
  8. };
  9.  
  10. response.Headers.CacheControl = new CacheControlHeaderValue
  11. {
  12. Public = true,MaxAge = TimeSpan.FromSeconds(15)
  13. };
  14.  
  15. return response;
  16. }
  17.  
  18. // returns in the response: "Cache-Control: public,max-age=15"

猜你在找的asp.Net相关文章