我有一个MVC控制器和一个创建菜单的类,这些菜单中的项必须仅显示给具有特定角色的用户以执行控制器的操作。在下面的例子中,我不想向使用Role2的用户显示详细信息的菜单项。我最终要做的是在菜单项上指定相同的角色,与我已经在控制器上指定的角色相同。所以我有两个定义角色的地方,它们必须是相同的,所以很容易出错。
我想做的是以某种方式从控制器那里获得角色,但我不知道如何做到这一点,或者这是否可能。
[Authorize(Roles = "Role1,Role2")]
public class MyController
{
public IActionResult Index()
{
return View();
}
[Authorize(Roles = "Role1")]
public IActionResult Details(int? id)
{
...
return View(...);
}
}
public class MenuItem
{
public string Action { get; set; }
public string Controller { get; set; }
public string Roles { get; set; }
}
...
var item = new MenuItem
{
Action = "Index",
Controller = "MyController",
Roles = "Role1,Role2", <---- this is what I do now.
Roles = GetRoles(MyController.Index.AuthorizedRoles) <---- this is what I need.
}; 发布于 2020-01-31 03:57:26
你的MenuItem的这个工厂方法怎么样?
public class MenuItem
{
public string Action { get; private set; }
public string Controller { get; private set; }
public string Roles { get; private set; }
private MenuItem() { }
public static MenuItem For<TMethod>(TMethod method) where TMethod : Delegate
{
var methodInfo = method.GetMethodInfo();
var attributes = methodInfo
.GetCustomAttributes(typeof(AuthorizeAttribute))
.Cast<AuthorizeAttribute>();
// If no attribute is defined on the action method, check the controller itself
if (attributes.Count() == 0)
{
attributes = methodInfo.DeclaringType
.GetCustomAttributes(typeof(AuthorizeAttribute))
.Cast<AuthorizeAttribute>();
}
return new MenuItem
{
Action = methodInfo.Name,
Controller = methodInfo.DeclaringType.Name,
Roles = string.Join(',', attributes.Select(a => a.Roles))
};
}
}这可以像这样调用:
var menuItem = MenuItem.For<Func<IActionResult>>(MyController.Details);https://stackoverflow.com/questions/59991990
复制相似问题