后台用户管理

管理部分的页面放在文件夹admin中,为保证不被非法访问,在该目录下添加一个web.config文件,其代码如下:

View Code
1 <?xml version="1.0"?>
2 <configuration>
3 <system.web>
4 <authorization>
5 <allow roles="Administrators"/>
6 <deny users="*"/>
7 </authorization>
8 </system.web>
9 </configuration>
1.用户管理页面 (~/Admin/ManagerUsers.aspx)

a:显示注册用户数、在线用户数

b:按“字母表”方式查找该字母为首字母的用户名。All链接用来显示全部用户。

   查找功能实现按用户名或E-mail地址模糊查用户。

c:查到的用户记录用表格显示。

该页面的源视图代码:

View Code
 1 <%@ Page Title="" Language="C#" MasterPageFile="~/Template.Master" AutoEventWireup="true" 
2 CodeBehind="ManageUsers.aspx.cs" Inherits="成员配置系统.admin.ManageUsers" %>
3 <asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
4 </asp:Content>
5 <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
6 <h3>账户管理</h3>
7 <p>
8 -注册用户数:<asp:Label ID="lblUsersCount" runat="server"></asp:Label><br />
9 -在线用户数:<asp:Label ID="lblOnLineCount" runat="server"></asp:Label></p>
10 点击下面的字母表查看以该字母开头的用户记录!<br /><br />
11 <asp:Repeater ID="rptAlphas" runat="server"
12 onitemcommand="rptAlphas_ItemCommand">
13 <ItemTemplate>
14 <asp:LinkButton ID="lnkAlpha"
15 Text="<%#Container.DataItem %>" CommandArgument="<%#Container.DataItem %>" runat="server">
16 </asp:LinkButton></ItemTemplate>
17 </asp:Repeater><br /><br />
18 根据用户名或则E-Mail地址模糊查询:<br />
19 <p>
20 <asp:DropDownList ID="ddlFind" runat="server">
21 <asp:ListItem>用户名</asp:ListItem>
22 <asp:ListItem>E-Mail</asp:ListItem>
23 </asp:DropDownList>匹配字符:<asp:TextBox ID="txtSearch" runat="server"></asp:TextBox>
24 <asp:Button ID="btnFind" runat="server" Text="模糊查询" onclick="btnFind_Click" />
25 </p>
26 <asp:GridView ID="gvUsers" runat="server" AutoGenerateColumns="False"
27 EnableModelValidation="True" EmptyDataText="" DataKeyNames="UserName"
28 onrowdeleting="gvUsers_RowDeleting">
29 <Columns>
30 <asp:BoundField DataField="UserName" HeaderText="用户名"
31 SortExpression="UserName" />
32 <asp:HyperLinkField DataNavigateUrlFields="Email"
33 DataNavigateUrlFormatString="mailto:{0}" DataTextField="Email"
34 HeaderText="邮件" />
35 <asp:BoundField DataField="CreationDate" DataFormatString="{0:f}"
36 HeaderText="注册日期" SortExpression="CreationDate" />
37 <asp:BoundField DataField="LastActivityDate" DataFormatString="{0:d}"
38 HeaderText="上次访问日期" SortExpression="LastActivityDate" />
39 <asp:CheckBoxField DataField="IsApproved" HeaderText="是否认证"
40 SortExpression="IsApproved" />
41 <asp:HyperLinkField DataNavigateUrlFields="UserName" Text="<img src='../images/Edit.gif'/>"
42 DataNavigateUrlFormatString="EditUser.aspx?UserName={0}"
43 DataTextField="UserName" HeaderText="编辑用户" />
44 <asp:TemplateField ShowHeader="False">
45 <ItemTemplate>
46 <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False"
47 CommandName="Delete" onclientclick="return confirm('确认是否删除该用户资料及其用户帐号?');"
48 Text="删除"></asp:LinkButton>
49 </ItemTemplate>
50 </asp:TemplateField>
51 </Columns>
52 <EmptyDataTemplate>
53 没有找到匹配的用户记录!
54 </EmptyDataTemplate>
55 </asp:GridView>
56 </asp:Content>

对应的后置代码如下:

View Code
public partial class ManageUsers : System.Web.UI.Page
{
MembershipUserCollection allUsers = Membership.GetAllUsers();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
lblUsersCount.Text = allUsers.Count.ToString();
lblOnLineCount.Text = Membership.GetNumberOfUsersOnline().ToString();

rptAlphas.DataSource = "A;B;C;D;E;F;G;H;I;J;K;L;M;N;O;P;Q;R;S;T;U;V;W;X;Y;Z;All".Split(';');
rptAlphas.DataBind();
}
}

protected void rptAlphas_ItemCommand(object source, RepeaterCommandEventArgs e)
{
gvUsers.Attributes.Add("SearchByEmail", false.ToString());
if (e.CommandArgument.ToString().Length == 1)
{
gvUsers.Attributes.Add("SearchByText", e.CommandArgument.ToString() + "%");
}
else
gvUsers.Attributes.Add("SearchByText", "");
BindUsers(false);
}

protected void BindUsers(bool refresh)
{
if (refresh)
{
allUsers = Membership.GetAllUsers();
lblUsersCount.Text = allUsers.Count.ToString();
lblOnLineCount.Text = Membership.GetNumberOfUsersOnline().ToString();
}
MembershipUserCollection users = null;
if (bool.Parse(gvUsers.Attributes["SearchByEmail"]))
{
//根据邮箱模糊查询
users= Membership.FindUsersByEmail(gvUsers.Attributes["SearchByText"]);
}
else
{
//根据字母查询或用户名查询---SearchByText
string searchText = gvUsers.Attributes["SearchByText"];
if (searchText.Length == 0)
{
users = allUsers;
}
else
{
users = Membership.FindUsersByName(searchText);
}
}
gvUsers.DataSource = users;
gvUsers.DataBind();
}

protected void btnFind_Click(object sender, EventArgs e)
{
gvUsers.Attributes["SearchByEmail"] = (ddlFind.SelectedValue == "E-Mail").ToString();
gvUsers.Attributes["SearchByText"] = "%" +txtSearch.Text +"%";
BindUsers(false);
}

protected void gvUsers_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string userName= gvUsers.DataKeys[e.RowIndex].Value.ToString();

System.Web.Profile.ProfileManager.DeleteProfile(userName);//删除用户资料内容(不要忘记)

Membership.DeleteUser(userName);//删除用户帐号

BindUsers(true);

}
}

运行该页面:

由于该页面受到访问限制,所以按照web.config设置先跳转到LoginDemo.aspx页面进行表单认证。

 

登录成功后,该Login控件会自动跳转到原始访问页面(ManageUsers.aspx),其实地址栏中的QueryString参数ReturnUrl表明的原始地址。

点击[ALL]链接后:

点击字母T,显示:

选择下拉框:E-Mail,匹配字符填写 “2”,如图:

点击删除链接,注意用户数的变化:

该页面功能测试通过!【注意:如果登录的用户不属于(Administrators角色,是无法正常访问的!)】

 

2.编辑用户页面 (~/Admin/EditUser.aspx)

该页面源视图代码:

View Code
<%@ Page Title="" Language="C#" MasterPageFile="~/Template.Master" AutoEventWireup="true" CodeBehind="EditUser.aspx.cs" Inherits="成员配置系统.admin.EditUser" %>
<%@ Register src="../Controls/UserProfile.ascx" tagname="UserProfile" tagprefix="uc1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
修改用户信息
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<h3>用户通用信息</h3>

<table class="style1">
<tr><td>用户名:</td>
<td><asp:Label ID="lblUserName" runat="server"></asp:Label></td>
</tr>
<tr>
<td>E-mail:</td>
<td>
<asp:HyperLink ID="lnkEmail" runat="server">[lnkEmail]</asp:HyperLink>
</td>
</tr>
<tr>
<td>注册日期:</td>
<td><asp:Label ID="lblRegisterDate" runat="server"></asp:Label></td>
</tr>
<tr>
<td>上次登录日期:</td>
<td><asp:Label ID="lblLastLoginDate" runat="server"></asp:Label> </td>
</tr>
<tr>
<td>上次访问日期:</td>
<td><asp:Label ID="lblLastActivity" runat="server"></asp:Label></td>
</tr>
<tr>
<td>是否在线:</td>
<td><asp:CheckBox ID="chkOnLine" runat="server" Enabled="False" /></td>
</tr>
<tr>
<td>认证通过:</td>
<td><asp:CheckBox ID="chkApproved" runat="server" AutoPostBack="True"
oncheckedchanged="chkApproved_CheckedChanged" /></td>
</tr>
<tr>
<td>解锁用户:</td>
<td><asp:CheckBox ID="chkLockedOut" runat="server" AutoPostBack="True"
oncheckedchanged="chkLockedOut_CheckedChanged" /></td>
</tr>
</table>
<h3>分配用户角色</h3>
<asp:CheckBoxList ID="chkRolesList" runat="server" RepeatColumns="5"
RepeatDirection="Horizontal">
</asp:CheckBoxList>

<p>创建新角色:
<asp:TextBox ID="txtRoleName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator
ID="RequiredFieldValidator1" ControlToValidate="txtRoleName"
SetFocusOnError ="true" ValidationGroup="CreateRole"
runat="server" ErrorMessage="角色名不能为空!"></asp:RequiredFieldValidator>
<asp:Button ID="btnCreateRole" ValidationGroup="CreateRole"
runat="server" Text="创建角色" onclick="btnCreateRole_Click" />&nbsp;&nbsp;
<asp:Button ID="btnAssignRoles" runat="server" Text="属于选中角色"
onclick="btnAssignRoles_Click" /></p>
<h3>编辑用户资料:</h3>
<uc1:UserProfile ID="UserProfile1" runat="server" /><br />
<asp:Button ID="btnSaveProfile" runat="server" Text="保存用户资料"
onclick="btnSaveProfile_Click" />
<hr />
<asp:Literal ID="lblInfo" runat="server"></asp:Literal>
</asp:Content>

对应的后置代码:

View Code
public partial class EditUser : System.Web.UI.Page
{
string userName;
protected void Page_Load(object sender, EventArgs e)
{
userName = Request["UserName"];
if (!IsPostBack)
{

MembershipUser user = Membership.GetUser(userName);
this.lnkEmail.Text = user.Email;
lnkEmail.NavigateUrl = "mailto:" + user.Email;
lblLastActivity.Text = user.LastActivityDate.ToString("f");
lblLastLoginDate.Text = user.LastActivityDate.ToString("g");
lblRegisterDate.Text = user.LastLoginDate.ToString("d");
lblUserName.Text = userName;

chkLockedOut.Checked = user.IsLockedOut;
chkOnLine.Checked = user.IsOnline;
chkApproved.Checked = user.IsApproved;
chkLockedOut.Enabled = user.IsLockedOut;

BindRoles();

UserProfile1.UserName = userName;

}

}

protected void BindRoles()
{
chkRolesList.DataSource = Roles.GetAllRoles();
chkRolesList.DataBind();

foreach (string role in Roles.GetRolesForUser(userName))
{
chkRolesList.Items.FindByText(role).Selected = true;
}
}

protected void btnCreateRole_Click(object sender, EventArgs e)
{
if (!Roles.RoleExists(txtRoleName.Text.Trim()))
{
Roles.CreateRole(txtRoleName.Text.Trim());
BindRoles();
}
}

protected void btnAssignRoles_Click(object sender, EventArgs e)
{
//先删除该用户所拥有的角色,再分配该用户所选中的角色
Roles.RemoveUserFromRoles(userName, Roles.GetRolesForUser(userName));

List<string> selectRoles = new List<string>();
foreach(ListItem item in chkRolesList.Items)
{
if (item.Selected) selectRoles.Add(item.Text);
}
Roles.AddUserToRoles(userName, selectRoles.ToArray());
}

protected void btnSaveProfile_Click(object sender, EventArgs e)
{
UserProfile1.SaveProfile();
}

protected void chkApproved_CheckedChanged(object sender, EventArgs e)
{
MembershipUser user = Membership.GetUser(userName);
user.IsApproved = chkApproved.Checked;
Membership.UpdateUser(user);
}

protected void chkLockedOut_CheckedChanged(object sender, EventArgs e)
{
if (!chkLockedOut.Checked)
{
MembershipUser user = Membership.GetUser(userName);
user.UnlockUser();
chkLockedOut.Enabled = false;
}
}
}

运行ManagerUser.aspx,用[张鲁鲁]登录,查所有用户[All链接],单击“方小小”链接:

 

创建一个新角色[Editors]创建成功!选中第一个角色和第三个角色[Editors],点击[属于选中角色]按钮,出现异常:

因为:一开始[方小小]用户没有任何角色,所以,Roles.GetRolesForUser(userName)的数组长度为0,代码进行如下改动:

View Code
 1 protected void btnAssignRoles_Click(object sender, EventArgs e)
2 {
3 //先删除该用户所拥有的角色,在分配该用户所选中的角色
4 string[] currentRoles = Roles.GetRolesForUser(userName);
5 if (currentRoles.Length >0)
6 Roles.RemoveUserFromRoles(userName, currentRoles);
7
8 List<string> selectRoles = new List<string>();
9 foreach(ListItem item in chkRolesList.Items)
10 {
11 if (item.Selected) selectRoles.Add(item.Text);
12 }
13 Roles.AddUserToRoles(userName, selectRoles.ToArray());
14 }
再次测试,通过!

那么【方小小】由于分配了Administrators角色,也可以访问ManagerUser.aspx了!

如果该页面的认证通过:设置为不选中,则该用户无法正常登录了!

测试一下:用户被锁定的情况,先看看web.config对应的配置:

输入5次密码错误,将会造成被锁定10分钟!(只能通过解锁方式解锁)进行测试!

posted @ 2011-12-28 20:36  net小虫  阅读(666)  评论(1编辑  收藏  举报