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.
For your isAjaxRequest, you should just be able to use: