简体   繁体   中英

MVC Filter Action Redirect

I've tried this 2 different ways

This way works but processes all of the code for the action before performing the redirect. This causes an issue where ever we are using the anti forgery token

    public class CheckAjaxRequestAttribute : ActionFilterAttribute
{
    private const string AJAX_HEADER = "X-Requested-With";

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        bool isAjaxRequest = filterContext.HttpContext.Request.Headers[AJAX_HEADER] != null;
        if (!isAjaxRequest)
        {
            filterContext.HttpContext.Response.Redirect("/");
        }
    }
}

The second way I've seen recommend I receives the following error "Child actions are not allowed to perform redirect actions."

        public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        filterContext.HttpContext.Response.Buffer = true;
        bool isAjaxRequest = filterContext.HttpContext.Request.Headers[AJAX_HEADER] != null;
        string redirectUrl = string.Format("{0}://{1}/", filterContext.HttpContext.Request.Url.Scheme, filterContext.HttpContext.Request.Url.Authority);
        if (!isAjaxRequest)
        {
            //filterContext.HttpContext.Response.Redirect("/");
            filterContext.Result = new RedirectResult(redirectUrl);

        }
    }
}

The purpose of this is to prevent the partial views from loading when not being called via ajax. The code works but the redirects errors and our security scan catches the issue when the @Html.AntiForgeryToken() throws an error.

Any help would be greatly appreciated.

对于您的isAjaxRequest,您应该可以使用:

filterContext.HttpContext.Request.IsAjaxRequest();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM