Get list of custom attributes for current action/controller in ASP.NET MVC

DavGarcia picture DavGarcia · Aug 25, 2010 · Viewed 22.1k times · Source

Checking out the sample code from http://lukesampson.com/post/471548689/entering-and-exiting-https-with-asp-net-mvc written for ASP.NET MVC2, I noticed they can check if a custom attribute is applied to the current action or controller by accessing filterContext.ActionDescriptor and filterContext.ActionDescriptor.ControllerDescriptor respectively:

public class ExitHttpsIfNotRequiredAttribute : FilterAttribute, IAuthorizationFilter {
    public void OnAuthorization(AuthorizationContext filterContext) {
        // snip

        // abort if a [RequireHttps] attribute is applied to controller or action
        if(filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof(RequireHttpsAttribute), true).Length > 0) return;
        if(filterContext.ActionDescriptor.GetCustomAttributes(typeof(RequireHttpsAttribute), true).Length > 0) return;

        // snip
    }
}

What would be the ASP.NET MVC 1 method of checking the action and controller for a custom attribute? In ASP.NET MVC 1 there is no filterContext.ActionDescriptor that I can tell.

Answer

Sunday Ironfoot picture Sunday Ironfoot · Dec 2, 2012

Even better and more reliable* approach:

filterContext.ActionDescriptor.GetCustomAttributes(
    typeof(RequireHttpsAttribute), true).Count> 0

Though this might be MVC 3.0+ only.