SmoothFriction.nl

posts - 39, comments - 20, trackbacks - 0

Monday, October 05, 2009

ASP.NET MVC: Access an action only by ajax

In a standard ‘web 2.0’ (god, I hate that buzzword) web application, you’ll often have ajax calls to your code. I prefer using jQuery, but any method will do. A proper ajax request will set a header value in the HTTP GET request, and ASP.NET is a good boy and catches that. By checking if the IsAjaxRequest() method on the request returns true.

This feature can be utilized for something I like to do on my ajax-exclusive controller actions: restrict access in such a way that only ajax requests can call the action. Other actions will get a 404, which effectively means the action will never be indexed by search engine crawlers, for one. To do this, I think a good way is to follow the convention set by the framework itself on restricting the actions to certain verbs (GET, POST): use an attribute on the method!

So how do we do this? It’s very simple actually. ASP.NET MVC provides a bunch of extension points, and this is one of them. There’s an class in the framework called ‘ActionMethodSelectorAttribute’, which contains only one method, which returns true if the call is permitted, false if it isn’t. On each call to an action, the framework checks for any attributes on the method which implement this class, and makes sure all of these return true. Simply put: we’ll implement the class in such a way that it will return true when the action is called via ajax:

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

I told you it was simple. Now you can use this attribute in your controllers, as such:

public class HomeController : Controller
{
    [AjaxRequest]
    public ActionResult Index()
    {
        return View();
    }
}

Yes, this is a silly example. It demonstrates the functionality though. When you go to /Home via your web browser now, you will get a 404, page does not exist. However, when you call /Home via ajax, you’ll get the HTML output from the view returned. That’s it.

posted @ Monday, October 05, 2009 12:00 PM | Feedback (1) | Filed Under [ c# asp.net mvc ]