Skip to content

Instantly share code, notes, and snippets.

@danielgreen
Created May 29, 2013 12:49
Show Gist options
  • Save danielgreen/5670031 to your computer and use it in GitHub Desktop.
Save danielgreen/5670031 to your computer and use it in GitHub Desktop.
A filter that can be applied to an MVC action to specify that either Ajax or non-Ajax requests should not be allowed.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Mvc;
namespace SFR.TOR.Web.Filters
{
/// <summary>
/// Represents an attribute that is used to restrict an action method so that the method is blocked from
/// handling Ajax requests, or non-Ajax requests, or both (in which case see NonActionAttribute).
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class AjaxRequestAttribute : FilterAttribute, IAuthorizationFilter
{
/// <summary>
/// Initializes a new instance of the SFR.TOR.Web.Filters.AjaxRequestAttribute class.
/// </summary>
/// <param name="ajaxAllowed">Sets whether Ajax requests are allowed</param>
/// <param name="nonAjaxAllowed">Sets whether non-Ajax requests are allowed</param>
public AjaxRequestAttribute(bool ajaxAllowed, bool nonAjaxAllowed)
{
this.AjaxAllowed = ajaxAllowed;
this.NonAjaxAllowed = nonAjaxAllowed;
}
/// <summary>
/// Gets whether Ajax requests are allowed
/// </summary>
public virtual bool AjaxAllowed { get; protected set; }
/// <summary>
/// Gets whether non-Ajax requests are allowed
/// </summary>
public virtual bool NonAjaxAllowed { get; protected set; }
public void OnAuthorization(AuthorizationContext filterContext)
{
var isAjaxRequest = filterContext.HttpContext.Request.IsAjaxRequest();
if (isAjaxRequest && !AjaxAllowed)
throw new InvalidOperationException("This action method cannot be invoked with Ajax requests.");
if (!isAjaxRequest && !NonAjaxAllowed)
throw new InvalidOperationException("This action method cannot be invoked with non-Ajax requests.");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment