ASP.NET MVC中的AntiforgeryToken在异常情况下重定向时的应用问题

12
我已经在我的ASP.NET MVC表单中实现了防伪标记(AnitforgeryToken),并在我的登录过程中添加了该属性。但是当检查失败时,我希望重定向到我的欺诈操作而不是异常页面。这种做法在该属性内可行吗?谢谢。
2个回答

21

如果您不想在所有带有[ValidateAntiForgeryToken]的操作上放置[HandleError]属性,您可以向全局过滤器添加自定义过滤器:

在Global.asax文件中Application_Start()下:

FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

然后:

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
        filters.Add(new AntiForgeryTokenFilter());
    }
}

AntiForgeryTokenFilter.cs:

public class AntiForgeryTokenFilter : FilterAttribute, IExceptionFilter
{
    public void OnException(ExceptionContext filterContext)
    {
        if(filterContext.Exception.GetType() == typeof(HttpAntiForgeryException))
        {
            filterContext.Result = new RedirectResult("/"); // whatever the url that you want to redirect to
            filterContext.ExceptionHandled = true;
        }
    }
}

13

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