0
votes

I am using the Angular project template with ASP.NET Core. Reference

The caching should be enabled by default, to be sure I have added an StaticFileOptions object to the StaticfileMiddleware:

public class Startup
{
 ...
 app.UseStaticFiles(new StaticFileOptions
 {
     OnPrepareResponse = ctx =>
         {
             const int durationInSeconds = 60 * 60 * 24;
             ctx.Context.Response.Headers[HeaderNames.CacheControl] =
              "public,max-age=" + durationInSeconds;
         }
 });
 ...
}

Then I have created an test.html in wwwroot folder.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset=utf-8>
  <title>Test static files</title>
</head>
<body>
    This is a test for static files!
</body>
</html>

When I dotnet run and navigate to https://localhost:5001/test.html the page is displayed correctly.

test.html

After I change the html page, I click to google chrome's address bar and press enter, to issue another HTTP request to the test.html file. I have not reload the page.

test.html after change

You can see that the change is reflected by google chrome and I received an status 200 again instead of 304. Cache-control in the Response Header is public,max-age=86400. Why does the static file caching not work? My desired result would be that the change is not reflected after the second HTTP request, so I can be sure static file caching is working properly.

I am using: .NET Core SDK 3.1.201 and Chrome 80.0.3987.163.

1
Cache headers are not sent (or more appropriately, are overwritten) in development. - Chris Pratt
@Chris Pratt Thank you for your answer. I have changed the hosting environment for my asp.net project to production and build the angular app with production option but I receive the same result, the static file caching still doesn't work. - carboneum

1 Answers

0
votes

I found the solution. You have to trust the ASP.NET Core HTTPS development certificate. Click here for details and then run the application. Navigate to your static file. Open a new tab in Chrome. Open the Chrome DevTools by pressing F12. Type the URL into the address bar or copy and paste it from the previous tab. It works!