首页 > 解决方案 > 防伪和缓存控制标头 ASP.NET 核心

问题描述

我正在尝试覆盖cache-control默认设置的 asp.net core 2.0 防伪标头

.net 核心始终将其设置为no-cache, no-store. 我正在尝试使用private它实际上可以按我的意愿工作。no-cache, no-store似乎并不总是能antiforgery token was meant for ... user..偶尔给我一些错误。哪个设置cache-control似乎private可以解决。

但是 .net 核心不允许我覆盖cache-control防伪设置的默认值。

我试过以下:

  public async Task<IActionResult> Login(string returnUrl)
  {
          HttpContext.Response.Headers.Append(Microsoft.Net.Http.Headers.HeaderNames.CacheControl, "private");
       ....
  }

 public class NoCacheAttribute : ActionFilterAttribute
 {
       public override void OnResultExecuting(ResultExecutingContext context)
       {
        // tried both
        //context.HttpContext.Response.Headers.Add(HeaderNames.CacheControl, "private");
        //context.HttpContext.Response.Headers[HeaderNames.CacheControl] = "private";
       }
 }

注意:现在仅用于 http

标签: c#asp.net-coreasp.net-core-2.0cache-controlantiforgerytoken

解决方案


Using antiforgery protection requires the Cache-Control: no-cache, no-store header. The page with the token absolutely cannot be cached under any circumstances ever because the token is regenerated for each request of that resource and the right one has to be sent back in order to validate. In other words, it absolutely must be requested fresh from the server every single time. The private value is not good enough, as it still allows caching in certain scenarios.

The reason for your error is the user authentication status has changed, after the page was loaded and before the form is submitted. This could be caused by either user being logged in or logged out. The antiforgery token uses the authenticated user as part of itself, so if the user's authentication status changes, the token will no longer be valid after submitting. If the user logs in or logs out, you will need to ensure that the page is refreshed so that a new antiforgery cookie can be set.


推荐阅读