ASP.NET MVC – Attribute to analyze calling controller and action

I needed to create an ASP.NET MVC attribute to attach to my controllers and have them affect all actions. The attribute would apply like so:

[ScottAuthorize]
public class AdvisoriesController : BaseController {
    // Really important business logic
}

What the attribute needed to do was analyze the controller and action being referenced, look up in a database whether the user actually had access to those actions (a custom role management system), and then grant or deny access based on the results. Here is a bit of that attribute to show how I did that:

public class ScottAuthorizeAttribute : System.Web.Mvc.AuthorizeAttribute {
    protected override bool AuthorizeCore(HttpContextBase httpContext) {
        string controller = httpContext.Request.RequestContext.RouteData.Values["controller"].ToString();
        string action = httpContext.Request.RequestContext.RouteData.Values["action"].ToString();
        // Really important authorization stuff
        return true; // Or false, of course.
    }
}

If you are so awed by this code that you want to pay me, I’ll give you an address and you can send cash. I only accept pennies from 1970 – 1980 in good condition.

Advertisements
  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: