Search code examples
asp.netasp.net-core-mvc

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


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")
    });
}

Solution

  • 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/bootstrap.css?@DateTime.Now.Ticks" />
        <link rel="stylesheet" href="~/css/site.css?@DateTime.Now.Ticks" />
    </environment>