asp.net-mvc – “后退”按钮和防伪令牌

我收到与反伪造属性相关的运行时错误

执行以下步骤:

>创建一个MVC Web应用程序并启动
>注册joe@acme.org
>退出
>注册jane@acme.org
>退出
>登录为joe@acme.org
>点击后退按钮
>登录为jane@acme.org

错误:提供的反伪造令牌是针对与当前用户不同的基于声明的用户

可以做什么来防止发生这种错误

解决方法

这是忽略错误并将用户返回到登录屏幕的一种方式。这只是一个例子。

创建一个名为HandleAntiforgeryTokenErrorAttribute的类继承自HandleErrorAttribute。覆盖OnException方法

public class HandleAntiforgeryTokenErrorAttribute : HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {
        filterContext.ExceptionHandled = true;
        filterContext.Result = new RedirectToRouteResult(
            new RouteValueDictionary(new { action = "Login",controller = "Account" }));
    }
}

转到您的FilterConfig类并将该属性注册为全局过滤器。

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
        filters.Add(new HandleAntiforgeryTokenErrorAttribute()
            { ExceptionType = typeof(HttpAntiForgeryException) }
        );
    }
}

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....