前面几篇介绍了如何使用角色,这一篇简单的讲一下如何使用角色进行限制使用。我们在网站中建一个文件夹“Admin”里面建一个Admin.aspx页面,在Web.config里做一下设置对此文件夹进行保护
<location path="Admin">
<system.web>
<authorization>
<deny users="?"/>
</authorization>
</system.web>
</location>
<location path="Admin">
<system.web>
<authorization>
<allow roles="Admin" />
<allow roles="Director" />
<allow roles="Member" />
<deny users="*"/>
</authorization>
</system.web>
</location>
以上有三个角色可以访问Admin(Admin,Director,Member)之后来看一下我们Admin/Admin.aspx页面,我在里页放了三个Button按钮,假设三个按钮的功能分别为:“查看”,“添加”,“删除”:

<%...@ Page Language="C#" AutoEventWireup="true" CodeFile="Admin.aspx.cs" Inherits="Admin_Admin" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>无标题页</title>
</head>
<body>
<form id="form1" runat="server">
<div style="text-align: center">
Administrator
</div>
<P>
<asp:TextBox ID="TextBox1" runat="server">Data</asp:TextBox> </P>
<p>
<asp:Button ID="Button1" runat="server" Text="查看" />
<asp:Button ID="Button2" runat="server" Text="添加" />
<asp:Button ID="Button3" runat="server" Text="删除" /></p>
</form>
</body>
</html>
我们希望对三种角色的权限做如下分配:Admin角色可以使用:“查看”,“添加”,“删除”三种功能,而Director角色只能使用:“查看”,“添加”功能,Member角色只能使用:“查看”功能,好了现在我们在代码页里写入权限代码:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Admin_Admin : System.Web.UI.Page

...{
protected void Page_Load(object sender, EventArgs e)

...{
if (!IsPostBack)

...{
if (Roles.IsUserInRole("Admin"))

...{
Button1.Visible = true;
Button2.Visible = true;
Button3.Visible = true;
}
else if (Roles.IsUserInRole("Member"))

...{
Button1.Visible = true;
Button2.Visible = false;
Button3.Visible = false;
}
else if (Roles.IsUserInRole("Director"))

...{
Button1.Visible = true;
Button2.Visible = true;
Button3.Visible = false;
}
}
}
}
在代码页里我们使用Roles类的IsUserInRole方法来判断当前登录用户是否属于我们指定的角色,如果是Admin角色就把三个按钮的可视设为true(这段不要也行,因为页面默认就是true),Director角色把“查看”“添加”两个按钮可视设为true“删除”的可视为false也就不能使用“删除”按钮功能,Member只有“查看”按钮可视为true其他两个按钮都是false都不可用,这样一来,每次打开页里的时候就会根据当前用户的角色来限制他所能使用的按钮功能,对于.NET中的其他控件都可以用这种方法进行限制,我用的这种方法也许不是太好,如果大家有更好的方法也说出来大家分享一下







上面的设置对Admin文件夹进行了保护所有未登录的用户都不能够访问这个文件夹里的页面,但是这种限制的面太广,比如Admin文件夹里放的都是网站系统管理页,在实际使用过程中管理员是分为多个不同等级的,比如论坛里的版主、坛主等等都有管理权限,而他们的管理权限大小不同,他们都能够访问Admin文件夹里的页面,但是版主只能对他所在的版进行管理,坛主则可以对所有版进行管理,当然我们也可以设置多个文件夹给每个文件夹不同的访问权限,但在实际使用中有时文件夹设的太多反而不利于管理,当多个角色都能访问同一文件夹的时候我们如何针对不同角色的权限来进行细小的限制管理呢?我个人一般采用如下方法,首先在Web.config里设置好允许访问该文件夹的角色:













































































