如何在页面加载时设置 MVCSitemapnode 角色 属性?

How do you set MVCSitemapnode roles property on page load?

所以我有一个 mvcsitemap:

<mvcSiteMapNode id="Home" title="Home" controller="Home" action="Index">
    <mvcSiteMapNode title="Page2" controller="Page2" action="Index"/>
    <mvcSiteMapNode title="Page3" controller="Page3" action="Index" />
    <mvcSiteMapNode title="Page4" controller="Pag4" action="Index" />
</mvcSiteMapNode>

我想做的是在加载站点时,我想根据数据库中的值分别设置每个节点的 "Roles" 属性。示例:

我希望可以从以下角色访问主节点:管理员、用户 我希望可以从以下角色访问 Page2 节点:User

不确定它是否如您所愿,但您可以只做一个您认为的条件吗??像这样

 @if (this.User.IsInRole("Admin")){ <mvcSiteMapNode title="Page2"
 controller="Page2" action="Index"/>} else
 if(this.User.IsInRole("User"))....

根据 documentation,roles 属性用于与 ASP.NET 的迭代操作。它不应该用于 MVC 安全,主要是因为 MVC 不保护物理页面,而是 MVC 保护 resources(通常是控制器操作)。 ASP.NET 安全方案基于底层文件系统,因此完全不适用于 MVC。

MVC 安全性基于 AuthorizeAttribute. You can subclass AuthorizeAttribute to provide any security scheme you need, including reading settings from the database on each round trip if that is what you really want. See this article 一种此类方法。

但请注意,默认 AuthorizeAttribute 实现支持控制器操作上的角色和用户,这将是一个性能更好的解决方案。

[Authorize(Roles="Administrators,SuperUsers")]
public ActionResult ChangePassword(ChangePasswordModel model)
{
    ...
}

一旦您的安全性基于 AuthorizeAttribute(或 AuthorizeAttribute 的子类),MvcSiteMapProvider 将自动与之交互。您唯一需要做的就是 turn on security trimming.

内部 DI (web.config)

<appSettings>
    <add key="MvcSiteMapProvider_SecurityTrimmingEnabled" value="true"/>
</appSettings>

外部 DI(MvcSiteMapProvider 模块)

bool securityTrimmingEnabled = true; // Near the top of the module