asp.net MVC antiforgerytoken on exception RedirectToAction

后端 未结 2 1818
梦如初夏
梦如初夏 2021-02-08 05:11

I have implimented the AnitforgeryToken with my asp.net MVC forms, and also added the attribute to my login procedure, however when the check failes i wish to redirect to my fra

2条回答
  •  我寻月下人不归
    2021-02-08 05:33

    In case you do not want to put [HandleError] attribute on all actions that have [ValidateAntiForgeryToken], you may add a custom filter to your Global filters:

    in Global.asax under Application_Start():

    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    

    and then:

    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;
            }
        }
    }
    

提交回复
热议问题