尽管在响应对象上配置了高速缓存控制标头,但它们仍未响应

gb2*_*b2d 17 c# http-caching asp.net-web-api

我正在尝试在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)
        {
            //...
        }
    }
Run Code Online (Sandbox Code Playgroud)

响应

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
Run Code Online (Sandbox Code Playgroud)

pkm*_*iec 6

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

您可能在项目中有一些改变缓存设置的魔法(想想全局操作过滤器或类似的东西).或者您可能正在通过代理重写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"
Run Code Online (Sandbox Code Playgroud)


gb2*_*b2d 5

几周后得到的答案是:

运行调试版本时,Cache-Control 标头似乎设置为“私有” 。当我使用发布版本运行时,问题就消失了。