You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Cookie(键为‘route’)过期致ASP.NET MVC 4反伪造令牌解密错误求解决

解决ASP.NET MVC 4 Cookie过期导致的反伪造令牌解密错误

1. 配置固定的加密验证密钥

在Web.config中添加<machineKey>节点,指定固定的验证和解密密钥,避免自动生成密钥带来的不一致问题(即使单服务器环境也建议配置,防止应用重启或Cookie过期后令牌验证失败):

<configuration>
  <system.web>
    <machineKey 
      validationKey="生成的验证密钥" 
      decryptionKey="生成的解密密钥" 
      validation="SHA1" 
      decryption="AES" />
  </system.web>
</configuration>

可通过PowerShell生成安全密钥:

# 生成验证密钥
[System.Web.Security.MachineKey]::GenerateKey()
# 生成解密密钥
[System.Web.Security.MachineKey]::GenerateDecryptionKey()

2. 捕获异常并处理过期Cookie

自定义反伪造令牌验证过滤器,捕获HttpAntiForgeryException并清除过期的routeCookie,避免错误提示:

public class ValidateAntiForgeryTokenWithCleanupAttribute : ValidateAntiForgeryTokenAttribute
{
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        var lastError = filterContext.HttpContext.Server.GetLastError();
        if (lastError is HttpAntiForgeryException)
        {
            // 清除过期的route Cookie
            filterContext.HttpContext.Response.Cookies["route"].Expires = DateTime.Now.AddDays(-1);
            // 重定向回当前请求页面
            filterContext.Result = new RedirectResult(filterContext.HttpContext.Request.Url.PathAndQuery);
            filterContext.HttpContext.Server.ClearError();
        }
        else
        {
            base.HandleUnauthorizedRequest(filterContext);
        }
    }
}

在需要验证的Action上替换默认过滤器:

[ValidateAntiForgeryTokenWithCleanup]
[HttpPost]
public ActionResult SubmitForm()
{
    // 业务逻辑代码
    return View();
}

3. 同步Cookie与令牌的有效期

调整routeCookie的过期时间,使其与反伪造令牌的有效期匹配,避免Cookie提前过期导致令牌验证失败:

var routeCookie = new HttpCookie("route")
{
    Value = "你的路由值",
    Expires = DateTime.Now.AddHours(24), // 设置合理的有效期
    HttpOnly = true,
    Secure = true // 生产环境建议启用HTTPS并开启此选项
};
Response.Cookies.Add(routeCookie);

内容的提问来源于stack exchange,提问作者Xuân Điền Nguyễn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 16:05:35