Asp.Net中成员、角色配置的具体步骤:
1)做好网站规划,访问权限相同的页面放到同一个文件夹中;
2)用C:/WINDOWS/Microsoft.NET/Framework/v2.0.50727/aspnet_regsql.exe将成员资格与角色管理的数据库并入网站数据库
3)修改网站的配置文件web.config,示例如下:
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<!-- 数据库连接字串 -->
<add name="HappyBookShopConnectionString" connectionString="Data Source=localhost/sqlexpress;Initial Catalog=db_CRM;uid=sa;pwd=sa" providerName="System.Data.SqlClient"/>
</connectionStrings>
<system.web>
<!-- 采用Forms身份验方式 -->
<authentication mode="Forms">
<forms loginUrl="~/login.aspx" defaultUrl="~/default.aspx">
</forms>
</authentication>
<!-- 自定义成员资格配置参数 -->
<membership defaultProvider="SqlProvider">
<providers>
<clear />
<add name="SqlProvider" type="System.Web.Security.SqlMembershipProvider,System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="HappyBookShopConnectionString" applicationName="news" minRequiredPasswordLength="1" minRequiredNonalphanumericCharacters="0"/>
</providers>
</membership>
<roleManager enabled="true">
<providers>
<clear/>
<add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider,System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="HappyBookShopConnectionString" applicationName="news"/>
</providers>
</roleManager>
<compilation debug="true"/>
</system.web>
</configuration>
具体可参照C:/WINDOWS/Microsoft.NET/Framework/v2.0.50727/CONFIG/machine.config
4)启动asp.net网站配置向导,新建角色、用户,将用户加入到角色中,为角色添加访问规则。
5)CreateUserWizard控件属性:
ContinueDestinationPageUrl:单击“继续”按钮时要重定向到的URL。
若要在代码中将某个新注册用户加入到某个角色中,可用如下的代码:
protected void CreateUserWizard1_CreatedUser(object sender, EventArgs e)
{
Roles.AddUserToRole(CreateUserWizard1.UserName, "teacher");
}
6)将一个LoginView控件拖到页面中
6.1 配置LoginView控件的AnonymousTemplate模版,可直接拖入一个Login控件,作为用户登录的入口
6.2 配置LoginView控件的LoggedInTemplate模版,可直接拖入LoginName控件和LoginStatus控件
6.3 如有必要,也可以用Login控件执行自定义身份验证:
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
//验证之前的其他处理代码
if (Membership.ValidateUser(Login1.UserName, Login1.Password)
e.Authenticated = true;
else
e.Authenticated = false;
}
如果e.Authenticated = true,表明登录有效,Login控件会触发LoggedIn事件,讲用户重定向到当前页或DestinationPageUrl属性指定的页,否则触发LoginError事件。
其他用API进行控制的代码可参照MSDN。
(7)如果不用系统的Login控件,可以自行编写代码进行身份验证:
protected void btnLogin_Click(object sender, EventArgs e)
{
if ((txtUserName.Text == "test") && (txtPwd.Text == "1234"))
{
//将用户登录凭据保存到Cookie中,注意,用户名进行了转换
FormsAuthentication.SetAuthCookie("SystemManager", false);
//显示网站主页
Response.Redirect("~/Default.aspx");
}
else
lblInfo.Text = "错误的用户名或密码!";
}
(8)显示用户信息:
获取用户标识:Membership.GetUser().ProviderUserKey.ToString();
Response.Write("<p>当前用户名称:" + Context.User.Identity.Name);
Response.Write("<p>当前用户授权方式:" + Context.User.Identity.AuthenticationType);
Response.Write("<p>当前用户是否已被验证:" + Context.User.Identity.IsAuthenticated.ToString());
密码恢复及修改可以参考:http://blog.csdn.net/lzyzsd/archive/2009/11/24/4860605.aspx