gpt4 book ai didi

c# - ASP.NET MVC : How to find Controllers with [Authorize] attributes using Reflection in C#?(或如何构建动态 Site.Master 菜单?)

转载 作者:太空狗 更新时间:2023-10-29 17:54:18 25 4
gpt4 key购买 nike

也许我应该在深入讨论标题问题之前备份并扩大范围......

我目前正在 ASP.NET MVC 1.0 中编写 Web 应用程序(尽管我的 PC 上确实安装了 MVC 2.0,所以我并不完全限于 1.0)——我已经开始使用标准 MVC 项目其中包含基本的“欢迎使用 ASP.NET MVC”,并在右上角显示 [主页] 选项卡和 [关于] 选项卡。非常标准,对吧?

我添加了 4 个新的 Controller 类,我们称它们为“天文学家”、“生物学家”、“化学家”和“物理学家”。 [Authorize] 属性附加到每个新的 Controller 类。

例如,对于 BiologistController.cs

[Authorize(Roles = "Biologist,Admin")]
public class BiologistController : Controller
{
public ActionResult Index() { return View(); }
}

这些 [Authorize] 标签自然地限制哪些用户可以根据角色访问不同的 Controller ,但我想在网站顶部动态构建一个菜单。基于用户所属角色的母版页.因此,例如,如果“JoeUser”是角色“天文学家”和“物理学家”的成员,则导航菜单会显示:

[Home] [Astronomer] [Physicist][About]

当然,它不会列出指向“生物学家”或“化学家” Controller 索引页面的链接。

或者如果“JohnAdmin”是角色“Admin”的成员,则指向所有 4 个 Controller 的链接将显示在导航栏中。

好吧,你大概明白了......现在是真正的问题......


the answer from this StackOverflow topic about Dynamic Menu building in ASP.NET 开头,我试图了解我将如何充分实现这一点。 (我是新手,需要更多指导,所以请多多包涵。)

答案建议扩展 Controller 类(称之为“ExtController”),然后让每个新的 WhateverController 继承自 ExtController。

我的结论是,我需要在此 ExtController 构造函数中使用反射来确定哪些类和方法附加了 [Authorize] 属性以确定角色。然后使用静态字典,将角色和 Controller /方法存储在键值对中。

我想象它是这样的:

public class ExtController : Controller
{
protected static Dictionary<Type,List<string>> ControllerRolesDictionary;

protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
// build list of menu items based on user's permissions, and add it to ViewData
IEnumerable<MenuItem> menu = BuildMenu();
ViewData["Menu"] = menu;
}

private IEnumerable<MenuItem> BuildMenu()
{
// Code to build a menu
SomeRoleProvider rp = new SomeRoleProvider();
foreach (var role in rp.GetRolesForUser(HttpContext.User.Identity.Name))
{

}
}

public ExtController()
{
// Use this.GetType() to determine if this Controller is already in the Dictionary
if (!ControllerRolesDictionary.ContainsKey(this.GetType()))
{
// If not, use Reflection to add List of Roles to Dictionary
// associating with Controller
}
}
}

这可行吗?如果是这样,我如何在 ExtController 构造函数中执行反射以发现 [Authorize] 属性和相关角色(如果有)

还有!随意超出此问题的范围,并提出解决此“基于角色的动态站点.主菜单”问题的替代方法。我是第一个承认这可能不是最佳方法的人。

编辑

经过大量阅读和试验,我想出了自己的解决方案。看下面我的回答。欢迎任何建设性的反馈/批评!

最佳答案

我更喜欢链接到我的菜单和 creating a HtmlHelper which checks to see if a link is accessible or not 中的所有内容基于 [Authorize] 属性。

关于c# - ASP.NET MVC : How to find Controllers with [Authorize] attributes using Reflection in C#?(或如何构建动态 Site.Master 菜单?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2999918/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com