系列文章导航:
温故知新ASP.NET 2.0(C#)(1) - MasterPage(母版页)
温故知新ASP.NET 2.0(C#)(1) - MasterPage(母版页)
温故知新ASP.NET 2.0(C#)(2) - Themes(主题)
温故知新ASP.NET 2.0(C#)(3) - SiteMap(站点地图)
温故知新ASP.NET 2.0(C#)(4) - 缓存&SqlCacheDependency
温故知新ASP.NET 2.0(C#)(5) - Localization
温故知新ASP.NET 2.0(C#)(8) - DataSourceControl
温故知新ASP.NET 2.0(C#)(6) - Membership&RoleManager
温故知新ASP.NET 2.0(C#)(7) - Profile
温故知新ASP.NET 2.0(C#)(8) - DataSourceControl
示例读取用户名和验证类型
Security/Test.aspx
Code
<%@ Page Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="Test.aspx.cs"
Inherits="Security_Test" Title="读取用户名和验证类型" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<p>
用户名称:
<%=User.Identity.Name %>
<br />
验证类型:
<%=User.Identity.AuthenticationType %>
</p>
</asp:Content>
Membership测试
App_Code/User.cs
Code
using System;
using System.Data;
using System.Configuration;
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;
using System.ComponentModel;
/**//// <summary>
/// User 的摘要说明
/// </summary>
[DataObject(true)]
public class User
{
public User()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
/**//// <summary>
/// 获得所有用户
/// </summary>
/// <returns></returns>
[DataObjectMethod(DataObjectMethodType.Select, true)]
public MembershipUserCollection GetMembers()
{
MembershipUserCollection muc = Membership.GetAllUsers();
return muc;
}
/**//// <summary>
/// 删除用户
/// </summary>
/// <returns></returns>
[DataObjectMethod(DataObjectMethodType.Delete, true)]
public void DeleteMember(string username)
{
Membership.DeleteUser(username, true);
}
}
Security/User.aspx
Code
<%@ Page Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="User.aspx.cs"
Inherits="Security_User" Title="Membership测试" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<p>
<asp:Label ID="lblMsg" runat="Server" ForeColor="red" />
</p>
<p>
用户名:
<asp:TextBox ID="txtUsername" runat="server"></asp:TextBox>
</p>
<p>
密 码:
<asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>
</p>
<p>
<asp:Button ID="btnSubmit" runat="server" Text="添加" OnClick="btnSubmit_Click" />
</p>
<p>
<asp:GridView ID="GridView1" runat="server" DataKeyNames="UserName" AutoGenerateColumns="False"
DataSourceID="ObjectDataSource1">
<Columns>
<asp:CommandField ShowDeleteButton="True" />
<asp:BoundField DataField="ProviderName" HeaderText="ProviderName" ReadOnly="True"
SortExpression="ProviderName" />
<asp:CheckBoxField DataField="IsOnline" HeaderText="IsOnline" ReadOnly="True" SortExpression="IsOnline" />
<asp:BoundField DataField="LastPasswordChangedDate" HeaderText="LastPasswordChangedDate"
ReadOnly="True" SortExpression="LastPasswordChangedDate" />
<asp:BoundField DataField="PasswordQuestion" HeaderText="PasswordQuestion" ReadOnly="True"
SortExpression="PasswordQuestion" />
<asp:CheckBoxField DataField="IsLockedOut" HeaderText="IsLockedOut" ReadOnly="True"
SortExpression="IsLockedOut" />
<asp:BoundField DataField="Comment" HeaderText="Comment" SortExpression="Comment" />
<asp:BoundField DataField="UserName" HeaderText="UserName" ReadOnly="True" SortExpression="UserName" />
<asp:BoundField DataField="Email" HeaderText="Email" SortExpression="Email" />
<asp:BoundField DataField="CreationDate" HeaderText="CreationDate" ReadOnly="True"
SortExpression="CreationDate" />
<asp:CheckBoxField DataField="IsApproved" HeaderText="IsApproved" SortExpression="IsApproved" />
<asp:BoundField DataField="LastLockoutDate" HeaderText="LastLockoutDate" ReadOnly="True"
SortExpression="LastLockoutDate" />
<asp:BoundField DataField="LastLoginDate" HeaderText="LastLoginDate" SortExpression="LastLoginDate" />
<asp:BoundField DataField="LastActivityDate" HeaderText="LastActivityDate" SortExpression="LastActivityDate" />
</Columns>
</asp:GridView>
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" SelectMethod="GetMembers"
TypeName="User" DeleteMethod="DeleteMember">
<DeleteParameters>
<asp:Parameter Name="username" Type="String" />
</DeleteParameters>
</asp:ObjectDataSource>
</p>
<p>
备注:<br />
用户和角色之间的操作如下<br />
Roles.AddUserToRole - 向角色添加用户<br />
Roles.RemoveUserFromRole - 从角色删除用户<br />
Roles.GetRolesForUser - 用户所属的角色列表<br />
</p>
</asp:Content>
Security/User.aspx.cs
Code
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 Security_User : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
MembershipCreateStatus status;
Membership.CreateUser(txtUsername.Text.Trim(), txtPassword.Text.Trim(), null, null, null, true, out status);
string strInsertMessage = "";
switch (status)
{
case MembershipCreateStatus.Success:
break;
case MembershipCreateStatus.DuplicateUserName:
strInsertMessage = "用户名重复";
break;
case MembershipCreateStatus.InvalidUserName:
strInsertMessage = "用户名输入错误";
break;
case MembershipCreateStatus.InvalidPassword:
strInsertMessage = "密码输入不符合要求";
break;
default:
strInsertMessage = "出现未知错误";
break;
}
if (strInsertMessage != "")
{
lblMsg.Text = strInsertMessage;
}
else
{
lblMsg.Text = "注册成功";
GridView1.DataBind();
}
}
}
RoleManager测试
App_Code/Role.cs
Code
using System;
using System.Data;
using System.Configuration;
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;
using System.Collections.Generic;
using System.ComponentModel;
/**//// <summary>
/// Role 的摘要说明
/// </summary>
[DataObject(true)]
public class Role
{
public Role()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
/**//// <summary>
/// 得到所有角色
/// </summary>
/// <param name="userName">用户名称</param>
/// <returns></returns>
[DataObjectMethod(DataObjectMethodType.Select, true)]
static public List<RoleData> GetRoles()
{
RoleData r = null;
List<RoleData> roleList = new List<RoleData>();
string[] ary = Roles.GetAllRoles();
foreach (string s in ary)
{
r = new RoleData();
r.RoleName = s;
roleList.Add(r);
}
return roleList;
}
/**//// <summary>
/// 删除角色
/// </summary>
/// <param name="roleName">角色名称</param>
[DataObjectMethod(DataObjectMethodType.Delete, true)]
static public void DeleteRole(string roleName)
{
MembershipUserCollection muc = Membership.GetAllUsers();
string[] allUserNames = new string[1];
foreach (MembershipUser mu in muc)
{
if (Roles.IsUserInRole(mu.UserName, roleName))
{
allUserNames[0] = mu.UserName;
Roles.RemoveUsersFromRole(allUserNames, roleName);
}
}
Roles.DeleteRole(roleName);
}
}
/**//// <summary>
/// 角色的实体类
/// </summary>
public class RoleData
{
protected string _roleName;
/**//// <summary>
/// 角色名称 关键字
/// </summary>
[DataObjectField(true)]
public string RoleName
{
get { return this._roleName; }
set { this._roleName = value; }
}
}
Security/Role.aspx
Code
<%@ Page Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="Role.aspx.cs"
Inherits="Security_Role" Title="RoleManager测试" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<p>
<asp:Label ID="lblMsg" runat="Server" ForeColor="red" />
</p>
<p>
角色名:
<asp:TextBox ID="txtRolename" runat="server"></asp:TextBox>
</p>
<p>
<asp:Button ID="btnSubmit" runat="server" Text="添加" OnClick="btnSubmit_Click" />
</p>
<p>
<asp:GridView ID="GridView1" runat="server" DataKeyNames="RoleName" DataSourceID="ObjectDataSource1" AutoGenerateColumns="False">
<Columns>
<asp:CommandField ShowDeleteButton="True" />
<asp:BoundField DataField="RoleName" HeaderText="RoleName" ReadOnly="True"
SortExpression="RoleName" />
</Columns>
</asp:GridView>
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" DeleteMethod="DeleteRole"
SelectMethod="GetRoles" TypeName="Role">
<DeleteParameters>
<asp:Parameter Name="roleName" Type="String" />
</DeleteParameters>
</asp:ObjectDataSource>
</p>
<p>
备注:<br />
用户和角色之间的操作如下<br />
Roles.AddUserToRole - 向角色添加用户<br />
Roles.RemoveUserFromRole - 从角色删除用户<br />
Roles.GetRolesForUser - 用户所属的角色列表<br />
</p>
</asp:Content>
Security/Role.aspx.cs
Code
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 Security_Role : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (Roles.RoleExists(txtRolename.Text.Trim()))
{
lblMsg.Text = "该角色已存在";
}
else
{
Roles.CreateRole(txtRolename.Text.Trim());
GridView1.DataBind();
}
}
}
注:需要用aspnet_regsql配置数据库