asp.net-mvcreflectionasp.net-mvc-4asp.net-mvc-filters

How does one get a list of authorization filters that have been applied to a particular controller action?


In an asp.net MVC application, a colleague is trying to build a role dependent set of UI elements in the web site's layout control, and my colleague wants to make an html extension that appears or doesn't based on the user's role relationship.

The colleague wants to be able to test the action that a particular link is linking to and check to see if the user is authorized to even visit that link. In order to do this it would be nice to run all of the authorization filters against the controller action.

In order to do this one must retrieve all of the authorization filters registered for a particular action.

Does anyone know how to grab just the authorization filters attributes associated with a particular controller action?


Solution

  • Something like this

    typeof(MyController).GetType()
    .GetMethod("action")
    .GetCustomAttributes(true)
    .Where(attr=>attr is IAuthorizationFilter).Cast<IAuthorizationFilter>()
    

    But you'll have to fake the filtercontext. Personally, I'd separate the filter functionality from the filter itself precisely for testing purposes. So you'd have the actual 'authorizator' object which would be called by the filter.