One feature I’m particulary fond of is the way the menu component adapts itselfs to the access rules you define for your users. In this post I’m going to explain how to set up a menu system which is controlled by roles without having to use the user/role providers.
First you need to have a sitemap, if you havent got one, go on and create one. This is simply done by choosing File -> New -> Site Map. Keep the default filename Web.sitemap, else .NET will not automatically find it later.
Example sitemap:
<?xml version="1.0" encoding="utf-8" ?>
<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0">
<siteMapNode url="" title="Root" description="">
<siteMapNode url="~/Default.aspx" title="Home" roles="*" description="" />
<siteMapNode url="~/Download.aspx" title="Download" roles="*" description="" />
<siteMapNode url="~/Messages.aspx" title="Messages" roles="User,Admin" description="" />
<siteMapNode url="~/Admin.aspx" title="Admin" roles="Admin" description="" />
</siteMapNode>
</siteMap>
As you probably can see, the roles are defined inside the sitemap (the roles attributes). We’re gonna use this later on in code to control which menu’s become visible and which not.
roles=”*” -> everyone can access this menu item
roles=”User,Admin” -> registered users and admins can access this menu item
roles=”Admin” -> only admins can access this menu item
Drop a menu to your page (masterpage preferably) and a SiteMapDataSource which will connect your menu to your sitemap. Set the DataSourceID to the id of the SiteMapDataSource you just dropped n your page. If all is good, you already should see the menu items displaying the contents of your sitemap file.
Next were gonna control what a user can see of the menu, depending on the role the user has. There must be some kind of role management system, but this can be really simple, like a field in the user database or you can even specify user names in the roles attributes of the sitemap file, though this would not be very maintainable.
Create an event handler for the menu’s MenuItemDataBound event by doubleclicking that event in the Property pane. In code now hide the menu items that you dont want to be accessed by a certain user/role:
protected void mainMenu_MenuItemDataBound(object sender, MenuEventArgs e)
{
SiteMapNode curNode = (SiteMapNode)e.Item.DataItem;
if (!curNode.Roles.Contains("*")) // if role="*", everyone can access the menuitem
{
if (!curNode.Roles.Contains(Session["Role"])) // On this occassion I have the role standby in a session variable
{
if (e.Item.Parent != null)
e.Item.Parent.ChildItems.Remove(e.Item);
else
mainMenu.Items.Remove(e.Item);
}
}
}
Thats it! You menu should now display or hide menu item depending on the role of the logged in user.
Geen opmerkingen:
Een reactie posten