RED
RED

Reputation: 13

ASP.NET Core web application hosted on IIS is caching CSS and other wwwroot content in a way a Ctrl+F5 won't refresh

I've generally released applications on .NET Framework 4.8 on IIS and have never had the problem I'm having with this ASP.NET Core 5.0 application.

In Startup.cs, I have:

app.UseStaticFiles();
app.UseStaticFiles(new StaticFileOptions()
{
    FileProvider = new PhysicalFileProvider("Fully/Qualified/Path"),
    RequestPath = new PathString("Relative/Path")
});

What is confusing me is that originally my wwwroot folder wasn't being added to the bin folder when I was building, yet it was still able to access the content. I did add to the .csproj the code below to force it into the bin directory whenever I build

<ItemGroup>
    <Content Update="wwwroot\**\*">
        <CopyToOutputDirectory>PreserveNewset</CopyToOutputDirectory>
    </Content>
</ItemGroup>

When I did the first delivery to our Cloud One Azure instance, everything worked as expected, but all subsequent deliveries would used the same original cached content within wwwroot and I'm stumped at what is holding on to it.

To take it a step further, we allow users to upload profile pictures to the site. The first picture they upload is correctly referenced and I can browse to the physical location on the server with the image and tell that it is correct. However, when I then upload a new image, logic on the server deletes the old image and replaces it with the new image - which I can verify on the servers file system directly - but the site will still permanently display the first image.

Upvotes: 0

Views: 37

Answers (1)

Tiny Wang
Tiny Wang

Reputation: 15906

I agree with @Kiron. According to the symptom you shared, we could know that it might result from cache, browser cache and server cache lead to that both F5 and Ctrl+F5 in browser doesn't load the latest profile image. Therefore, append version in each static resource request or just set <clientCache cacheControlMode="DisableCache" /> for <staticContent> will be a good workaround.

In the meantime, I think the best solution is to invalidate the cache only when needed, this makes the client and server to make the most usage of cache to reduce network traffic and improve performance. For example, if the users' profile names are the same for each single user, I think set policy="CacheUntilChange" might also deserve to take into consideration. And if you are working on scenarios that you don't require to update static file content in time, we could also set cacheControlMode="UseMaxAge" and cacheControlMaxAge="7.00:00:00" property.

And please note, the IIS settings are applied for the whole website by default, if we want to set cache policy only for static files or files in a specific folder, we might take a look at this case. It shares the <location path="images"> configuration for files only in wwwroot/images folder.

Upvotes: 0

Related Questions