ASP.NET MVC Action Filter – Ajax Only Attribute
The website I’m currently working on has a lot of AJAX incorporated in it, so my controller has a few actions which are only called in AJAX. At first I was using HttpContext.Request.IsAjaxRequest() within my action to control if the request was indeed an Ajax one, but I didn’t like the fact that I needed to call HttpContext in my control; it also made a lot of redundant code. That is why I decided to build an Action Filter that would do that for me.
Here’s the Action Filter
public class AjaxOnlyAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if(!filterContext.HttpContext.Request.IsAjaxRequest())
filterContext.HttpContext.Response.Redirect("/error/404");
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
}
}
And an implementation example
[AjaxOnly]
public ActionResult AjaxActionMethod()
{
....
}
This might not be the best solution, but works pretty good for me so far!
This entry was posted on Wednesday, May 27th, 2009 at 3:03 pm and is filed under ASP.NET, C#.NET, Developement, MVC. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.


Andrew Gunn May 28th, 2009 at 12:25 pm
Good article. Instead of hard-coding the 404 redirect, I’d change the response’s status code and let ASP.NET decide where the user should go:
filterContext.HttpContext.Response.StatusCode = 401;
Alternatively, you could wrap this up in a class that inherits from ActionResult (just like AuthorizeAttribute):
public class HttpNotFoundResult : ActionResult
{
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException(“context”);
}
context.HttpContext.Response.StatusCode = 401;
}
}
…and set the result of the filter context:
filterContext.Result = HttpNotFoundResult;
Hope this helps.