如何在ASP.NET Core RC2中禁用浏览器缓存?

37

我尝试使用这个中间件,但浏览器仍在保存文件。

我希望用户始终能够获取最新版本的js和css文件。

public void Configure(IApplicationBuilder app)
{
    app.UseSession();
    app.UseDefaultFiles();
    app.UseStaticFiles(new StaticFileOptions
    {
        OnPrepareResponse = context =>
            context.Context.Response.Headers.Add("Cache-Control", "no-cache")
    });
}
5个回答

46

尝试添加一个Expires头部:

app.UseStaticFiles(new StaticFileOptions()
{
    OnPrepareResponse = context =>
    {
        context.Context.Response.Headers.Add("Cache-Control", "no-cache, no-store");
        context.Context.Response.Headers.Add("Expires", "-1");
    }
});
另一种方法是在开发过程中向请求的末尾添加一个更改的查询字符串,这种情况下不需要中间件。

另一种方法是在开发过程中向请求的末尾添加一个更改的查询字符串,这种情况下不需要中间件。

<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>

11
如果您使用Headers.Add(),那么如果中间件已经添加了头,则会失败,因此请使用Response.Headers["Cache-Control"] = "no-cache, no-store, must-revalidate, max-age=0"等方式。 - Stefan Steiger

45

在ASP.NET Core中禁用浏览器缓存:

public class HomeController : Controller
{
    [ResponseCache(NoStore =true, Location =ResponseCacheLocation.None)]
    public IActionResult Index()
    {
        return View();
    }
}

15

另一种方法是在链接文件时使用 ASP 特性,在 _Layout.cshtml 中使用 asp-append-version,每次文件更改时都会添加一个新的哈希值,因此写成:

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

最终将导致:

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

所以您可以直接使用缓存功能和最新版本。


哈希在LinkTagHelper中定义,目前是SHA256哈希(SHA:安全哈希算法):https://dev59.com/slwX5IYBdhLWcg3w0iQc - Stefan Steiger

3
[ResponseCache(Location = ResponseCacheLocation.None, Duration = 0, NoStore = true)]

尝试在控制器类上面添加注释。这对我来说有效。

0
我遇到了同样的问题,但是发布的解决方案对我没有起作用。 有效的方法是我添加了一个中间件来添加头部信息。
    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();
    });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接