asp.net MVC antiforgerytoken异常RedirectToAction

dav*_*der 10 model-view-controller asp.net-mvc

我用我的asp.net MVC表单对AnitforgeryToken表示赞同,并且还将该属性添加到我的登录过程中,但是当检查失败时我希望重定向到我的欺诈行为而不是异常页面.这可能属于属性????

谢谢

Dmi*_*try 18

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

在Global.asaxApplication_Start():

FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
Run Code Online (Sandbox Code Playgroud)

然后:

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
        filters.Add(new AntiForgeryTokenFilter());
    }
}
Run Code Online (Sandbox Code Playgroud)

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Dar*_*rov 11

ValidateAntiForgeryTokenAttribute只会扔HttpAntiForgeryException.您可以使用HandleErrorAttribute来处理此场景:

[HandleError(
    ExceptionType = typeof(HttpAntiForgeryException), 
    View = "Unauthorized")]
[ValidateAntiForgeryToken]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult SomeActionThatRequiresToken() 
{
    return View();
}
Run Code Online (Sandbox Code Playgroud)