首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >获取在控制器的操作上指定的角色

获取在控制器的操作上指定的角色
EN

Stack Overflow用户
提问于 2020-01-31 02:05:41
回答 1查看 202关注 0票数 0

我有一个MVC控制器和一个创建菜单的类,这些菜单中的项必须仅显示给具有特定角色的用户以执行控制器的操作。在下面的例子中,我不想向使用Role2的用户显示详细信息的菜单项。我最终要做的是在菜单项上指定相同的角色,与我已经在控制器上指定的角色相同。所以我有两个定义角色的地方,它们必须是相同的,所以很容易出错。

我想做的是以某种方式从控制器那里获得角色,但我不知道如何做到这一点,或者这是否可能。

代码语言:javascript
运行
复制
[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.
}; 
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-01-31 03:57:26

你的MenuItem的这个工厂方法怎么样?

代码语言:javascript
运行
复制
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))
        };
    }
}

这可以像这样调用:

代码语言:javascript
运行
复制
var menuItem = MenuItem.For<Func<IActionResult>>(MyController.Details);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59991990

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档