11

I'm looking for a way to enforce a controller's action to be accessed only via an AJAX request.

What is the best way to do this before the action method is called? I want to refactor the following from my action methods:

if(Request.IsAjaxRequest())
    // Do something
else
    // return an error of some sort

What I'm envisioning is an ActionMethodSelectorAttribute that can be used like the [AcceptVerbs] attribute. I have no experience crating such a custom attribute though.

Remus
  • 1,433
  • 3
  • 14
  • 24

2 Answers2

17

Create an ActionFilter that fires OnActionExecuting

public class AjaxActionFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (!filterContext.HttpContext.Request.IsAjaxRequest())
            filterContext.Result = new RedirectResult(//path to error message);           
    }
}

Setting the filter's Result property will prevent execution of the ActionMethod.

You can then apply it as an attribute to your ActionMethods.

Dawid Kowalski
  • 1,197
  • 1
  • 9
  • 23
bmancini
  • 2,028
  • 15
  • 21
  • +1, of the ways presented, this is by and far the one closest to my preferred approach and is extensible, especially if sited in a basecontroller that all others inherit from – jim tollan Nov 13 '10 at 16:51
2

Its as simple as this:

public class AjaxOnly : ActionMethodSelectorAttribute
{
    public override bool IsValidForRequest(ControllerContext controllerContext, System.Reflection.MethodInfo methodInfo)
    {
        return controllerContext.HttpContext.IsAjaxRequest();
    }
}

I just forget where IsAjaxRequest() comes from, I'm pasting from code I have but "lost" that method. ;)

John Farrell
  • 24,673
  • 10
  • 77
  • 110
  • Ooops, didn't get the part about returning an error. This makes it so the method will never get his unless the request is Ajax. Just another way to do it. – John Farrell Nov 12 '10 at 20:43
  • I know this answer was posted aaaaaages ago but the IsAjaxRequest hangs off the request object not the Httpcontext. – heymega Jun 23 '15 at 10:32