How to disable browser cache in ASP.NET core rc2?
Asked Answered
O

5

37

I tried this Middleware but the browser still saving files.

I want user will always get the last version of js and css files.

public void Configure(IApplicationBuilder app)
{
    app.UseSession();
    app.UseDefaultFiles();
    app.UseStaticFiles(new StaticFileOptions
    {
        OnPrepareResponse = context =>
            context.Context.Response.Headers.Add("Cache-Control", "no-cache")
    });
}
Oval answered 6/7, 2016 at 18:56 Comment(0)
K
46

Try adding an Expires header as well:

app.UseStaticFiles(new StaticFileOptions()
{
    OnPrepareResponse = context =>
    {
        context.Context.Response.Headers.Add("Cache-Control", "no-cache, no-store");
        context.Context.Response.Headers.Add("Expires", "-1");
    }
});

Another approach would be to add a querystring that changes to the end of your requests in development. Middleware would not be required in this case.

<environment names="Development">
    <link rel="stylesheet" href="~/lib/bootstrap/dist/css/[email protected]" />
    <link rel="stylesheet" href="~/css/[email protected]" />
</environment>
Kabuki answered 6/7, 2016 at 22:53 Comment(1)
If you do Headers.Add(, then it will fail if a middleware already added the header, therefore, use Response.Headers["Cache-Control"] = "no-cache, no-store, must-revalidate, max-age=0"; etc.Svensen
F
45

Disabling browser cache in ASP.NET core:

public class HomeController : Controller
{
    [ResponseCache(NoStore =true, Location =ResponseCacheLocation.None)]
    public IActionResult Index()
    {
        return View();
    }
}
Footing answered 14/3, 2017 at 17:24 Comment(0)
A
16

Another way would be using an ASP-Attribute when you link your files in your _Layout.cshtml by using asp-append-version you will add a fresh hash everytime the file changed, so writing:

<script src="~/js/minime.js" asp-append-version="true"></script>

will in the end lead to:

<script src="/js/minime.js?v=Ynfdc1vuMOWZFfqTjfN34c2azo3XiIfgfE-bba1"></script>

so you get caching and the latest version out of the box.

Avulsion answered 21/12, 2016 at 12:57 Comment(1)
The hash is defined in LinkTagHelper, currently a SHA256-hash (SHA: Secure Hash Algorithms): #33343143Svensen
U
3
[ResponseCache(Location = ResponseCacheLocation.None, Duration = 0, NoStore = true)]

Try adding an annotation above the controller class.It works for me.

Unbelt answered 18/8, 2021 at 18:52 Comment(0)
C
0

I had the same issue, but the posted solution didn't work for me. What was working is that I added a middleware, which adds the headers.

    app.Use(async (httpContext, next) =>
    {
        httpContext.Response.Headers[HeaderNames.CacheControl] = "no-cache, no-store, must-revalidate, max-age=0";
        httpContext.Response.Headers[HeaderNames.Expires] = "-1";
        await next();
    });
Connubial answered 6/7, 2023 at 5:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.