我正尝试在IIS API中设置缓存头,但是ASP.NET的响应表明设置的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
发布于 2015-08-01 02:45:06
下面的代码在普通WebApi应用程序(System.Web.Http 4.0.0.0)中正确设置了"cache-control: public,max-age=15“所以..。这可能不是WebApi本身导致的问题。
你可能在你的项目中有一些改变缓存设置的魔法(想想全局动作过滤器或类似的东西)。或者你正在使用proxy,它会重写HTTP报头。
public HttpResponseMessage Get()
{
var content = new JavaScriptSerializer().Serialize(new { foo = "bar" });
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(content, Encoding.UTF8, "application/json")
};
response.Headers.CacheControl = new CacheControlHeaderValue
{
Public = true,
MaxAge = TimeSpan.FromSeconds(15)
};
return response;
}
// returns in the response: "Cache-Control: public, max-age=15"
发布于 2017-03-09 20:23:21
要添加另一项可能导致此问题的内容:
你通过一个Owin管道运行。
在这种情况下,您需要在Owin中间件中设置headers,如下所示:
class MiddleWare : OwinMiddleware
{
public MiddleWare(OwinMiddleware next)
: base(next)
{
}
public override async Task Invoke(IOwinContext context)
{
context.Response.Headers["Cache-Control"] = "no-cache, no-store, must-revalidate";
context.Response.Headers["Pragma"] = "no-cache";
context.Response.Headers["Expires"] = "0";
await Next.Invoke(context);
}
}
https://stackoverflow.com/questions/31585376
复制相似问题