0

Using visual studio 2017, I created an asp.net core mvc 2.1 application, and added Response Caching.

In Index.cshtml, added

@DateTime.Now.ToString()

When I ran the application in a browser, if I reload the page, the output time will vary by each refresh, instead of caching 10000 seconds as specified in the code.

Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
//other code
    services.AddResponseCaching();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//other code
    app.UseResponseCaching();
}

Index action:

[ResponseCache(Duration = 10000, Location = ResponseCacheLocation.Any, VaryByQueryKeys = new string[] {"id"})]
public IActionResult Index()
{
    // fetch data from database
}

When I inspect the response header:

cache-control: public,max-age=10000

But still, when refreshing, the output varies each time.

Any advice is appreciated.

Edit: If I use another browser to open the link I can get a cached copy. However if I hit F5 to refresh, I get an updated time.

Second (F5 refreshed) request header:

GET / HTTP/1.1

Host: example.com

Connection: keep-alive

Cache-Control: max-age=0

Upgrade-Insecure-Requests: 1

User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,/;q=0.8

Referer: https://example.com/

Accept-Encoding: gzip, deflate, br

Accept-Language: en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7,ja;q=0.6

Cookie: blablabla

Cal
  • 747
  • 1
  • 13
  • 30
  • @mjwills If I hit F5 to refresh, then I get a new time. If I use a new browser tab or another browser, I get a cached copy. I don't understand, the location is set to any which means there should be a cached copy on server, regardless of browser behavior, it should always get same copy in 10000 seconds. – Cal Jan 03 '19 at 01:30
  • When you are hitting F5 the browser is likely sending a header to bypass the cache. If you can provide the info requested in my second comment that may be useful. – mjwills Jan 03 '19 at 02:03
  • @Cal `If I hit F5 to refresh, then I get a new time`- that's the point. asp.net core response cache store on browser, not in server and that's why you are getting new time always while you are hitting F5. – TanvirArjel Jan 03 '19 at 05:06
  • Is `app.UseResponseCaching();` above or below `app.UseMvc()`? The reason I ask is because the order matters. – juunas Jan 03 '19 at 06:43
  • `asp.net core response cache store on browser, not in server` https://learn.microsoft.com/en-us/aspnet/core/performance/caching/middleware?view=aspnetcore-2.2 certainly reads like the caching can be on the server. – mjwills Jan 03 '19 at 10:42
  • @Benl2 Thank you, I have used Code_Worm's fix in that thread, haven't done thorough testing but it seems to be working. – Cal Jan 03 '19 at 19:21

0 Answers0