所以我有一个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节点:用户

最佳答案

按照documentation,roles属性用于与ASP.NET进行迭代操作。不应将其用于MVC安全性,主要是因为MVC不保护物理页面,但是MVC保护资源(通常是控制器操作)。 ASP.NET安全方案基于基础文件系统,因此完全不足以与MVC一起使用。

MVC安全性基于AuthorizeAttribute。您可以对AuthorizeAttribute进行子类化,以提供所需的任何安全方案,包括在您真正想要的每次往返过程中从数据库中读取设置。请参阅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

10-06 02:44