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.

[AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
    public class OnlyAjaxRequestAttribute : ActionMethodSelectorAttribute
    {
        public override Boolean IsValidForRequest(ControllerContext context, MethodInfo info)
        {
            return context.HttpContext.Request.IsAjaxRequest();
        }
    }

Now the attribute is ready for decorating the action method

public class HomeController
{
   [OnlyAjaxRequest]
   public ActionResult Index()
   {
      //Do something
   }
}

Now you can decorate any action with this attribute to deny normal request.
You can find the full source code https://github.com/miroprocessor/Mirosoft.Utilities.Mvc

Comments

Post a Comment

Popular posts from this blog

ASP.Net MVC : ActionLink with bootstrap icon

ASP.Net MVC : Conditional Validation using ValidationAttribute

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