您几乎仅限于使用反射来获取任何属性信息,而不管包括 MVC 操作方法在内的任何内容。;)
获取此信息的唯一其他技术是通过 ControllerDescriptor 路径
在您的情况下,您可以完全跳过寻找授权属性,而只是询问用户是否被授权并为他们提供所需的母版页。
我之前在自定义视图引擎中动态设置了母版页,而性能最高的选项是查看任何可用的 HttpContextBase 信息。对于一种情况,当我需要使用它们时,我只是传递了查询参数或附加在 {masterPage} 路由参数上。
获取动作信息的唯一其他途径是 ReflectedControllerDescriptor 路由。这种方法的问题是它非常冗长,并且需要很多代码行才能完成您的工作。
这是用于进行安全链接修剪修剪的“描述符”技术的一些代码(我在 stackoverflow 上找到的!)。如果母版页位于自定义视图引擎中,此代码还可用于动态设置母版页。它不是您要寻找的,但可以帮助其他人在其他地方完成相同的动态母版页设置:
public static bool HasActionPermission( this HtmlHelper htmlHelper, string actionName, string controllerName )
{
//if the controller name is empty the ASP.NET convention is:
//"we are linking to a different controller
ControllerBase controllerToLinkTo = string.IsNullOrEmpty(controllerName)
? htmlHelper.ViewContext.Controller
: GetControllerByName(htmlHelper, controllerName);
var controllerContext = new ControllerContext(htmlHelper.ViewContext.RequestContext, controllerToLinkTo);
var controllerDescriptor = new ReflectedControllerDescriptor(controllerToLinkTo.GetType());
var actionDescriptor = controllerDescriptor.FindAction(controllerContext, actionName);
return ActionIsAuthorized(controllerContext, actionDescriptor);
}
private static bool ActionIsAuthorized(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
{
if (actionDescriptor == null)
return false; // action does not exist so say yes - should we authorise this?!
AuthorizationContext authContext = new AuthorizationContext(controllerContext);
// run each auth filter until on fails
// performance could be improved by some caching
foreach (IAuthorizationFilter authFilter in actionDescriptor.GetFilters().AuthorizationFilters)
{
authFilter.OnAuthorization(authContext);
if (authContext.Result != null)
return false;
}
return true;
}