Search code examples
asp.net-mvc-3action-filter

ASP.NET MVC ActionFilter - Determine if AJAX Request


I am using an ActionFilter to determine if a user has access to a specific resource such as an Account object (a la Rhino Security) before hitting an action. This is a global filter which redirects to an error page should the authorization value fail

I'm using the following code, which works fine for full page requests:

filterContext.Controller.TempData["ErrorMessage"] = string.Format("You are not authorized to perform operation: {0}", operation);
filterContext.Result = new RedirectResult("~/Error/AuthorizationError");

Ajax requests I do not want to apply a redirect, but rather return an error message. Is there a way to tell inside the action filter if this is an AJAX request or a regular full page (sorry not sure of the correct terminology) request?

Thanks in advance

JP


Solution

  • You could use the IsAjaxRequest extension method:

    if (filterContext.HttpContext.Request.IsAjaxRequest())
    {
        // it was an AJAX request
        ...
    }
    else
    {
        // it was a standard request
        filterContext.Controller.TempData["ErrorMessage"] = string.Format("You are not authorized to perform operation: {0}", operation);
        filterContext.Result = new RedirectResult("~/Error/AuthorizationError");
    }