我正在尝试为我的 ASP.NET MVC4 web 应用程序
构建一个动态菜单。在构建菜单时,我想确保用户不应访问的菜单项不会显示在菜单中。
我正在对每个需要给定角色的页面使用表单例份验证和 [Authorize]
属性。
给定两个字符串 (Controller 和 Action)
,以及一个登录用户,我如何确定用户是否有权访问该 Controller Action?
我所有的菜单数据都存储在数据库中。我呈现菜单的计划是构建菜单数据的 JSON 对象并将其嵌入到 View 中。然后在客户端,我将使用 Handlebars.js
并将菜单 JSON 对象
插入到模板中。
我正在尝试做的是在呈现菜单数据时检查用户对给定 Controller /操作的权限。我最初的想法是使用反射并查找 Controller 操作方法并检查授权属性是否存在,并检查当前登录的用户是否具有访问该页面的必要角色。如果不是,则不会呈现菜单项。
我总是不愿意使用反射
,然而,通常有一种更简单的做事方式。
最佳答案
public static IEnumerable<MethodInfo> GetActions(string controller, string action)
{
return Assembly.GetExecutingAssembly().GetTypes()
.Where(t =>(t.Name == controller && typeof(Controller).IsAssignableFrom(t)))
.SelectMany(
type =>
type.GetMethods(BindingFlags.Public | BindingFlags.Instance)
.Where(a => a.Name == action && a.ReturnType == typeof(ActionResult))
);
}
然后
var roles = ((AuthorizeAttribute) (GetActions("ControllerName" + "Controller", "ActionName").First().GetCustomAttributes(typeof (AuthorizeAttribute), false)[0])).Roles;
if(roles.Contains("admin or smth"))
{
doSomsing();
}
关于c# - 根据角色确定用户是否有权访问给定的 Controller 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14382336/