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

C# 如何在页面加载时设置MVCSitemapnode角色属性?,c#,asp.net-mvc,mvcsitemapprovider,C#,Asp.net Mvc,Mvcsitemapprovider,所以我有一个mvcsitemap: <mvcSiteMapNode id="Home" title="Home" controller="Home" action="Index"> <mvcSiteMapNode title="Page2" controller="Page2" action="Index"/> <mvcSiteMapNode title="Page3" controller="Page3" action="Index" />

所以我有一个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>

我想做的是,当加载站点时,我想根据数据库中的值单独设置每个节点的“角色”属性。例如:

我希望可以从以下角色访问主节点:Admin、User
我希望Page2节点可以从角色访问:User

不确定它是否与您的外观相同,但您可以在视图中执行一个条件吗??像这样

 @if (this.User.IsInRole("Admin")){ <mvcSiteMapNode title="Page2"
 controller="Page2" action="Index"/>} else
 if(this.User.IsInRole("User"))....
@if(this.User.IsInRole(“Admin”){}else
如果(this.User.IsInRole(“用户”)。。。。
根据,角色属性用于ASP.NET的ITropertability。它不应该用于MVC安全,主要是因为MVC不保护物理页面,而是MVC保护资源(通常是控制器操作)。ASP.NET安全方案基于底层文件系统,因此完全不适合与MVC一起使用

MVC安全性基于。您可以将
AuthorizeAttribute
子类化,以提供所需的任何安全方案,包括在每次往返时从数据库读取设置(如果这是您真正想要的)。请参见其中一种方法

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

[Authorize(Roles="Administrators,SuperUsers")]
public ActionResult ChangePassword(ChangePasswordModel model)
{
    ...
}
一旦您将安全性建立在
AuthorizeAttribute
(或
AuthorizeAttribute
的子类)上,
MvcSiteMapProvider
将自动与之交互。你唯一需要做的就是

内部DI(web.config)


我试图从数据库控制它,而不是硬编码任何值,因为特定角色可以访问的页面可能会经常更改。
<appSettings>
    <add key="MvcSiteMapProvider_SecurityTrimmingEnabled" value="true"/>
</appSettings>
bool securityTrimmingEnabled = true; // Near the top of the module