首先描述一下需求:
我們要做一個最簡單的網站。有三類用戶:匿名用戶,員工,管理員,網站結構如下:
admin目錄下的頁面只允許admin角色的用戶訪問,employee目錄下的頁面只允許emp角色的用戶訪問。Default.aspx允許所有用戶訪問。Login.aspx實現登陸功能,regUser.aspx實現註冊用戶功能。
1.首先我們新建一個網站
2.進入C:\WINDOWS\Microsoft.NET\Framework\v2.0.xxxxx這個目錄下,找到aspnet_regsql.exe,運行,並一路下一步,得到aspnetdb數據庫
3.打開網站,打開web.config文件,配置membership:
<providers>
<addname="mySqlMembershipProvider"
type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
connectionStringName="ConnectionString"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="false"
applicationName="TestMembership"
requiresUniqueEmail="true"
passwordFormat="Hashed"
maxInvalidPasswordAttempts="5"
minRequiredPasswordLength="6"
minRequiredNonalphanumericCharacters="0"
passwordAttemptWindow="10"
passwordStrengthRegularExpression=""/>
</providers>
</membership>
然後繼續添加連接字符串:
<addname="ConnectionString" connectionString="server=.;uid=sa;pwd=sa;database=aspnetdb"/>
</connectionStrings>
4.接着配置roleManager:
<providers>
<addname="myAspNetSqlRoleProvider"
connectionStringName="ConnectionString"
applicationName="TestMembership"
type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
</providers>
</roleManager>
5.接着在項目中添加兩個頁面,一個首頁Default.aspx一個登陸頁面Default.aspx,隨後繼續添加forms身份驗證的配置:
<formsloginUrl="Login.aspx"
protection="All"
timeout="30"
name=".ASPXAUTH"
path="/"
slidingExpiration="true"
defaultUrl="Default.aspx"
cookieless="UseDeviceProfile"/>
</authentication>
現在需要添加兩種角色employee、admin,添加角色的方法很簡單方法有很多,我們介紹最簡單的一種:新建一個頁面,在這個頁面的page_load事件當中加入如下代碼:
{
Roles.CreateRole("admin");
Roles.CreateRole("employee");
}
瀏覽一下這個頁面就添加了這倆角色。
添加完角色,就該實現註冊用戶功能了。
regUser頁面代碼如下:
<!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">
<tableborder="0" cellpadding="0" cellspacing="0">
<tr>
<td>用戶名:</td>
<td><asp:TextBoxrunat="server" ID="txtName"></asp:TextBox></td>
</tr>
<tr>
<td>密碼:</td>
<td><asp:TextBoxrunat="server" ID="txtPwd" TextMode="Password"></asp:TextBox></td>
</tr>
<tr>
<td>郵箱:</td>
<td><asp:TextBoxrunat="server" ID="txtEmail"></asp:TextBox></td>
</tr>
<tr>
<tdcolspan="2"><asp:Buttonrunat="server" ID="btnReg" Text="註冊"
onclick="btnReg_Click"/></td>
</tr>
</table>
</form>
</body>
</html>
這是regUser.aspx.cs文件中的代碼
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class regUser : System.Web.UI.Page
{
protectedvoid Page_Load(object sender, EventArgs e){}
protectedvoid btnReg_Click(object sender, EventArgs e)
{
/* 這裏僅僅是爲了演示Membership功能,所以驗證、錯誤捕獲等在此省略
* 由於我們在web.config中將requiresQuestionAndAnswer設爲false
* 所以在這裏只需要調用3個參數的重載即可
* */
Membership.CreateUser(txtName.Text, txtPwd.Text, txtEmail.Text);
//將剛剛註冊的用戶添加Employee角色
Roles.AddUserToRole(txtName.Text,"employee");
//註冊成功,將用戶跳轉到默認頁面
//所謂默認頁面,就是在前面配置時forms節點下defaultUrl指定的頁面
FormsAuthentication.RedirectFromLoginPage(txtName.Text,false);
}
}
ok,註冊功能已經差不多了,現在我們開始完成登錄頁面。
打開Login.aspx頁面,加上如下代碼:
<!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">
<tableborder="0" cellpadding="0" cellspacing="0">
<tr>
<td>用戶名:</td>
<td><asp:TextBoxrunat="server" ID="txtName"></asp:TextBox></td>
</tr>
<tr>
<td>密碼:</td>
<td><asp:TextBoxrunat="server" ID="txtPwd" TextMode="Password"></asp:TextBox></td>
</tr>
<tr>
<tdcolspan="2"><asp:Buttonrunat="server" Text="登錄" ID="btnLogin"
onclick="btnLogin_Click"/></td>
</tr>
</table>
</form>
</body>
</html>
Login.aspx.cs代碼如下:
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e){ }
protectedvoid btnLogin_Click(object sender, EventArgs e)
{
if (Membership.ValidateUser(txtName.Text, txtPwd.Text))
{
//登錄成功向瀏覽器寫入身份票據
FormsAuthentication.SetAuthCookie(txtName.Text,false);
//跳轉回最初請求的url或是默認url
//注:所謂最初請求的url是指:如果我未經登錄,
//直接訪問admin/admin.aspx這個頁面,那麼將會跳轉到該登錄頁面
//如果登錄成功,則此方法將會以登錄用戶的身份跳轉回
//admin/admin.aspx頁面
FormsAuthentication.RedirectFromLoginPage(txtName.Text,false);
}
else
{
ClientScript.RegisterStartupScript(this.GetType(),"", "alert('用戶名或密碼錯誤!');",true);
}
}
}
好了,註冊和登錄都已經完成了,剩下的任務就是配置訪問權限這一項了,其實很簡單:在admin和employee目錄下分別添加兩個web.config文件
admin目錄下的web.config內容如下:
<appSettings/>
<connectionStrings/>
<system.web>
<authorization>
<allowroles="admin"/>
<denyusers="*"/><!--*代表的是所有用戶-->
</authorization>
</system.web>
</configuration>
表示所有具有admin角色的用戶允許訪問,除此之外全部拒絕訪問。
employee目錄下的web.config內容如下:
<appSettings/>
<connectionStrings/>
<system.web>
<authorization>
<allow roles="employee"/>
<deny users="*"/>
</authorization>
</system.web>
</configuration>
好了,到這裏,我們實現的功能有:登錄,註冊,權限控制。一個網站所需要的功能基本上都已經實現了,項目有點簡單,但是功能齊全。一般來說80%的站點使用membership就足夠了。好了,本項目到此結束。