NoStore 没有将 Cache-Control 设置为 no-store

Sha*_*tin 1 caching asp.net-core

我们已经使用[ResponseCache(NoStore = true)]了我们的AccountController.Login行动。

[HttpGet]
[ResponseCache(NoStore = true)]
[AllowAnonymous]
public IActionResult Login(string returnUrl = null)
{
    ViewData["ReturnUrl"] = returnUrl;
    return View();
}
Run Code Online (Sandbox Code Playgroud)

根据文档:

NoStore覆盖大多数其他属性。当此属性设置为 时trueCache-Control标题将设置为"no-store"

在一个新的私有 Firefox 窗口中,当我们导航到 时~/Account/Login,我们会收到以下响应标头。

Cache-Control:"no-cache"
Content-Type:"text/html; charset=utf-8"
Date:"Mon, 26 Dec 2016 21:50:27 GMT"
Pragma:"no-cache"
Server:"Kestrel"
Transfer-Encoding:"chunked"
Run Code Online (Sandbox Code Playgroud)

我们使用的是 ASP.NET Core 1.1.0。我们如何将Cache-Control标题设置为no-store

Sha*_*tin 5

问题是 ASP.NET Core 防伪会破坏所有用户设置的标头并添加自己的. 为了克服这个问题,我们添加了自己的IHtmlGenerator.

// Startup.cs
services.AddSingleton<
    Microsoft.AspNetCore.Mvc.ViewFeatures.IHtmlGenerator, 
    OurHacks.HtmlGeneratorHack>();

// HtmlGeneratorHack.cs (subsclasses DefaultHtmlGenerator)
public override IHtmlContent GenerateAntiforgery(ViewContext viewContext)
{
    var result = base.GenerateAntiforgery(viewContext);

    viewContext
        .HttpContext
        .Response
        .Headers[HeaderNames.CacheControl] 
            = "no-cache, max-age=0, must-revalidate, no-store";

     return result;
}
Run Code Online (Sandbox Code Playgroud)