Restrict non-ajax requests using ActionMethodSelectorAttribute

In ASP.Net MVC each coming request is routed to a certain action method inside some controller and with JQuery it became piece of cake to call this action method using ajax. In some scenarios we need to restrict the incoming requests to be ajax request only, fortunately ASP.Net MVC represent a new method to Request object called IsAjaxRequest() that return true if the current request come from ajax call and return false if current request is normal request(typing url in address bar of a browser, click a link to this page,..etc).

We can use that method to deny any request come from ajax call or vise versa.
public class HomeController
{
   public ActionResult Index()
   {
      if(Request.IsAjaxRequest())
      {
        //Do something
      }
      else
      {
        //Do something else
      }
   }
}
As we see if we need to make this check many times in our project, we will rewrite the same if statement for each action we need it be called via ajax only, but is there another way to do this check with elegant manner?. One of elegant ways that will save rewriting this if statement is creating a new attribute that will decorate actions to deny any request except ajax request.

To create such attribute you must override IsValidForRequest method of ActionMethodSelectorAttribute class. All what you have to do is create a new class, its name will be the name of the new attribute, and it will inherit ActionMethodSelectorAttribute class, in the overriden IsValidForRequest method you can put your logic, in our case denying non-ajax requests.

C# version
public class AjaxRequest : ActionMethodSelectorAttribute
{
   public override Boolean IsValidForRequest(ControllerContext context , MethodInfo info)
   {
      if(!context.HttpContext.Request.IsAjaxRequest())
      {
         throw new Exception("Just Ajax request allowed");
      }
      return true;
   }
}
Now the attribute is ready for decorating the action method
public class HomeController
{
   [AjaxRequest]
   public ActionResult Index()
   {
      //Do something
   }
}
Now you can decorate any action with this attribute to deny normal request.

VB.Net version
Public Class AjaxRequest
    Inherits ActionMethodSelectorAttribute

    Public Overrides Function IsValidForRequest(ByVal controllerContext As ControllerContext, ByVal methodInfo As MethodInfo) As Boolean
        If Not controllerContext.HttpContext.Request.IsAjaxRequest Then
            Throw New Exception("Just Ajax Requests allowed")
        End If
        Return True
    End Function
End Class

Comments

Post a Comment

Popular posts from this blog

Android : How to change progress bar color at runtime programmatically?

How to fire RowCommand event of nested GridView?

ASP.Net MVC : Conditional Validation using ValidationAttribute