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

不羁岁月 提交于 2019-12-11 03:36:03

问题


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:


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.



来源:https://stackoverflow.com/questions/16270190/how-does-one-get-a-list-of-authorization-filters-that-have-been-applied-to-a-par

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!