Search code examples
c#cachingasp.net-core-3.1.net-6.0responsecache

ResponseCacheAttribute doesn't seem to stop preflight requests from hitting the server


I have the following attribute declaration over an action: [ResponseCache(Location = ResponseCacheLocation.Client, Duration = 1800)]

This works great - I can see the browser using disk cache instead of reading the information from the server again. However, it still fires off each preflight request for some reason. That's really unnecessary, and I'd like to get rid of this. How can I give the same cache treatment to the preflight request associated with this endpoint?

edit:

After seeing a suggestion below, I changed this:

    {
        builder
            .AllowCredentials()
            .SetIsOriginAllowedToAllowWildcardSubdomains()
            .WithOrigins("yadda");
    }

to this:

    {
        builder
            .AllowCredentials()
            .SetIsOriginAllowedToAllowWildcardSubdomains()
            .SetPreflightMaxAge(TimeSpan.FromHours(1))
            .WithOrigins("yadda");
    }

which resulted in this traffic in the network tab where I can see the OPTIONS request going out almost every time despite these requests all taking place within seconds of one another and the GET being retrieved from disk cache:

enter image description here

Here are the response headers which display:

enter image description here


Solution

  • Preflight requests are special and their caching time is not controlled by usual means but with special Access-Control-Max-Age header. Default caching time is 5 seconds. Browsers impose limits on this value:

    Firefox caps this at 24 hours (86400 seconds). Chromium (prior to v76) caps at 10 minutes (600 seconds). Chromium (starting in v76) caps at 2 hours (7200 seconds). The default value is 5 seconds.

    To set this header in asp.net core while configuring CORS, use SetPreflightMaxAge.