Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 447
JP. Avatar asked Dec 07 '11 20:12

JP.


People also ask

How can we identify Ajax request in ASP NET MVC?

Previously, ASP.NET MVC applications could easily check if a request was being made via AJAX, through the aptly named IsAjaxRequest() method which was an available method on the Request object, as shown below: public ActionResult YourActionName() { // Check if the request is an AJAX call.

Which determines whether or not the specified HTTP request is an Ajax request?

The X-Requested-With header returns a string that indicates whether it's an Ajax request or not. An Ajax request will have this header set to XMLHttpRequest.

Is Ajax a MVC?

As you might be knowing, Ajax is a shorthand for Asynchronous JavaScript and XML. The MVC Framework contains built-in support for unobtrusive Ajax. You can use the helper methods to define your Ajax features without adding a code throughout all the views.


1 Answers

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");
}
like image 189
Darin Dimitrov Avatar answered Oct 27 '22 22:10

Darin Dimitrov