gpt4 book ai didi

c# - 尽管在响应对象上配置了缓存控制 header ,但未在响应中发送

转载 作者:可可西里 更新时间:2023-11-01 03:01:38 25 4
gpt4 key购买 nike

我试图在 ASP.NET MVC Web API 中设置缓存 header ,但 IIS 的响应表明 CacheControl 值集被忽略了。

我最初的假设是我在 System.Web.Http.Cors 中使用了 EnableCorsAttribute,这在这个用例中是必需的。但是,即使没有该属性,响应 Cache-Control header 仍然是“私有(private)的”。

我这里有什么地方做错了吗?

    // 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

最佳答案

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

您的项目中可能有一些更改缓存设置的魔法(想想全局操作过滤器或类似的东西)。或者您可能正在通过重写 HTTP header 的代理。

    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"

关于c# - 尽管在响应对象上配置了缓存控制 header ,但未在响应中发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31585376/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com