【发布时间】:2015-07-23 10:58:15
【问题描述】:
我正在尝试在 ASP.NET MVC Web API 中设置缓存标头,但来自 IIS 的响应表明设置的 CacheControl 值被忽略。
我最初的假设是我在 System.Web.Http.Cors 中使用了 EnableCorsAttribute,这在这个用例中是必需的。但是,即使没有该属性,响应 Cache-Control 标头仍然是“私有的”。
我在这里做错了吗?
// GET api/<version>/content
// [EnableCors(origins: "*", headers: "*", methods: "*")]
public HttpResponseMessage Get(HttpRequestMessage request)
{
int cacheMaxAgeSeconds;
string cacheMaxAgeString = request.GetQueryString("cache-max-age") ?? request.GetQueryString("cache-max-age-seconds");
string rawUri = request.RequestUri.ToString();
try
{
cacheMaxAgeSeconds = cacheMaxAgeString == null ? Config.ApiCacheControlMaxSeconds : int.Parse(cacheMaxAgeString);
}
catch (Exception ex)
{
cacheMaxAgeSeconds = Config.ApiCacheControlMaxSeconds;
//...
}
try
{
//...
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent("...", Encoding.UTF8, "application/json")
};
response.Headers.CacheControl = new CacheControlHeaderValue
{
Public = true,
MaxAge = TimeSpan.FromSeconds(cacheMaxAgeSeconds)
};
return response;
}
catch (Exception apiEx)
{
//...
}
}
回应
HTTP/1.1 200 OK
Cache-Control: private
Content-Type: application/json; charset=utf-8
Date: Thu, 23 Jul 2015 10:53:17 GMT
Server: Microsoft-IIS/7.5
Set-Cookie: ASP.NET_SessionId=knjh4pncbrhad30kjykvwxyz; path=/; HttpOnly
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Content-Length: 2367
Connection: keep-alive
【问题讨论】:
-
您是否有理由尝试在github.com/filipw/AspNetWebApi-OutputCache 之类的东西上推出自己的产品?
-
是的,我实际上希望调用者能够指定缓存周期。该值从查询字符串中读取并馈送到缓存控制标头值中。
-
嗯,如果有人知道这个问题的答案,那将是 twitter.com/filip_woj(上述 nuget 包的创建者)可能值得在 Twitter 上与他联系。
-
好电话。在我这样做之前,我将浏览该项目,看看是否有任何不同的做法。当我有机会检查时会更新。
标签: c# asp.net-web-api http-caching