Search code examples
c#asp.net-web-apihttp-caching

Cache-Control headers not sent in response despite being configured on response object


I'm trying to set cache headers in ASP.NET MVC Web API, but the response from IIS suggests that the CacheControl values set are being ignored.

My original assumption was that I was using the EnableCorsAttribute in System.Web.Http.Cors, which is necessary in this use case. However, even without that attribute, the response Cache-Control header is still 'private'.

Is there something I am doing wrong here?

    // 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)
        {
            //...
        }
    }

Response

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

Solution

  • The answer, having picked this up some weeks later:

    Cache-Control header appears to be set to 'private' when running debug builds. The issue goes away when I run with a release build.