How does one get a list of authorization filters t

2019-07-20 07:18发布

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?

1条回答
Lonely孤独者°
2楼-- · 2019-07-20 07:27

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.

查看更多
登录 后发表回答