Ever wanted to restrict actions to only responding to Ajax requests?  How about restricting them through the use of a custom attribute?

You can do this through using the code below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Mvc;

namespace Common.Infrastructure.Attributes
{
    public class AjaxOnlyAttribute : ActionMethodSelectorAttribute
    {
        public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)
        {
            return controllerContext.RequestContext.HttpContext.Request.IsAjaxRequest();
        }
    }
}

The attribute simply returns true or false depending on if the request was generated through an Ajax call (i.e. “XmlHttpRequest” is in the request header).

Then to use the code, annotate your controller’s action like so:

public class DefaultController : Controller 
{
    [AjaxOnly]
    public ActionResult GetAjaxResult() 
    {
        // Ajax only content
    }
}