How do you set MVCSitemapnode roles property on page load?

286 views Asked by At

So I have an 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>

What I want to do is when the site is loaded I want to set the "Roles" attribute of each node inividually from values from a database. Example:

I want the Home node to be accessible from the roles: Admin, User I want the Page2 node to be accessible from the roles: User

2

There are 2 answers

0
NightOwl888 On BEST ANSWER

As per the documentation, the roles attribute is for iteroperability with ASP.NET. It is not supposed to be used for MVC security, primarily because MVC doesn't secure physical pages, but instead MVC secures resources (usually controller actions). The ASP.NET security scheme is based on the underlying file system and as a result is completely inadequate for use with MVC.

MVC security is based on the 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 for one such approach.

But do note that the default AuthorizeAttribute implementation supports roles and users on controller actions, which would be a better performing solution.

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

Once you base your security on AuthorizeAttribute (or a subclass of AuthorizeAttribute), MvcSiteMapProvider will automatically interact with it. The only thing you need to do is turn on security trimming.

Internal DI (web.config)

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

External DI (MvcSiteMapProvider Module)

bool securityTrimmingEnabled = true; // Near the top of the module
1
DarkVision On

not sure if it what you looking but can you just do a condition in your view ?? like this

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