哈,歡迎後 !我的名稱是 Parag Agarwal,我在這裡支援工程師在 Microsoft。本月份我們要討論另一個很棒的功能,在 Microsoft ASP.NET 2.0 管理登入控制項的提供者。
概觀
在本月的專欄中,我將探討下列主題:
- 登入控制項的簡短概觀
- 提供者模型在 ASP.NET 中的簡要概觀 2.0
- 逐步解說上建立自訂提供者可使用的登入控制項與現有的資料來源
登入控制項
這是很常見的需求,以在幾乎每一個 Web 應用程式中有登入功能。發行 ASP.NET 2.0 之前我們使用設計來驗證使用者的使用者介面 (UI)。這牽涉到撰寫許多多餘的程式碼。若要避免這個問題,ASP.NET 2.0 提供需要沒有程式設計的 Web 應用程式完成登入解決方案一大堆伺服器控制項的形式。在內部,這些控制項負責呈現適當的 UI,使用者可以輸入他或她的認證,並驗證它們。現在,我們不必設計網頁開發人員為使用者介面,而且我們不需要小心的驗證使用者藉由撰寫我們自己的程式碼。
登入 控制項所使用的基礎提供者模型會負責的。我們將會看到
登入 控制項來驗證使用者在下一節中的使用之提供者的方式。您可以找到登入控制項和我們如何可以使用它們在下列網站的相關資訊:
提供者模型
提供者模型可讓開發人員建置隨插即用軟體。 它基本上被為了提高從實作的抽象概念,讓這兩個部分可以獨立有所不同。若要執行此動作 ASP.NET 提供有所有抽象方法和屬性提供實作這些方法和屬性在衍生類別所實作所需特定抽象基底類別。
如需有關抽象的基底類別的詳細資訊,請造訪下列網站:
所以,來彙總,提供者會為媒介由控制項使用與資料存放區進行互動。它們會提供應用程式與資料來源之間的抽象概念的裝置驅動程式提供抽象從硬體裝置的方式相同。
因為我們將討論關於成員資格提供者的此發行項] 談什麼類別 ASP.NET 2.0 提供成員資格功能。ASP.NET 2.0 成員資格功能會定義稱為
MembershipProvider 類別的抽象基底類別。此外,
MembershipProvider 衍生自不同的基底類別稱為
ProviderBase 類別是一般類別到所有提供者。因此,開發人員可以衍生現有
MembershipProvider 類別來建立自己的提供者類別。
如需有關
MembershipProvider 和
ProviderBase 類別的詳細資訊,請造訪下列網站:
一旦我們已定義成員資格提供者,必須描述在組態檔中所有的 Web 應用程式) 的 Machine.config 或特定的 Web 應用程式) 的 Web.config 中。適當的提供者會從由 ASP.NET 組態檔中所提供的資訊的執行階段具現化。但是,它有可能在執行的階段以動態方式變更提供者。
如需有關指定成員資格提供者的組態設定的詳細資訊,請造訪下列網站:
現在,請
登入 控制項隨附使用特定的資料配置/資料結構的兩個內建的成員資格提供者:
- 使用中的目錄
關聯的提供者類別是 System.Web.Security.ActiveDirectoryMembershipProvider。 - Microsoft SQL Server
關聯的提供者類別是 System.Web.Security.SqlMembershipProvider。
不過,如果我們想要使用現有的資料庫結構,我們很容易可以程式碼以取得舊的資料庫結構和說話的登入控制項的自訂成員資格提供者。
建立自訂成員資格提供者
既然我們有足夠的資訊登入控制項和基礎他們使用的提供者模型上,讓我們來建立自訂成員資格提供者以取得現有的登入控制項工時與自訂資料存放區。
附註自訂提供者會使用稱為
TestDB 的 SQL Server 資料庫。
TestDB 會有命名為具有欄位使用者識別碼的
使用者、 使用者名稱,以及密碼和電子郵件識別碼] 和 [地址等其他資訊的資料表。
- 啟動 Microsoft Visual Studio 2005。
- 建立類別庫專案,並賦予一個的名稱,例如 CustomMembershipProviderLib。
- 將原始程式檔加入至專案,例如 CustomMembershipProvider.cs。
- 在 [參考] 區段中包含 System.Web 和 System.Configuration。
- 確認下列命名空間都包含在 [CustomMembershipProvider.cs 檔案
using System;
using System.Web;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web.Security;
using System.Collections.Specialized;
using System.Data.SqlClient;
- 繼承 CustomMembershipProvider 類別與 MembershipProvider class.
class CustomMembershipProvider :
MembershipProvider
- 我們已經知道所以屋 MembershipProvider 是估算因此我們需要覆寫 CustomMembershipProvider 類別中的所有抽象方法抽象的類別。會自動的 Visual Studio 2005 中沒有很酷的功能。當您延伸任何抽象類別,只在 抽象類別 上, 按一下滑鼠右鍵,然後再按 [實作抽象類別。這會自動將放所有抽象方法的宣告。您會注意到每個方法主體包含常見一行程式碼。
throw new Exception("The method or operation is not implemented."); 這表示自訂提供者支援哪些功能。
附註初始化 方法的實作是強制的。 - 自訂提供者中我們將會專注於提供一些功能,如下所示:
- 藉由使用 CreateUserWizard 控制項建立新的使用者
- 使用 登入 控制項來驗證使用者認證
我們將會一一實作這些功能。第一次,實作 初始化 方法。載入提供者時,ASP.NET 會呼叫這個方法。當而且,提供者時,就會載入應用程式將使用它們進行第一次,並且它們一次建立每個 public override void Initialize(string name,NameValueCollection config)
{
// Verify that config isn't null
if (config == null)
throw new ArgumentNullException("config");
// Assign the provider a default name if it doesn't have one
if (String.IsNullOrEmpty(name))
name = "AspNetCustomMembershipProvider";
// Add a default "description" attribute to config if the
// attribute doesn't exist or is empty
if (string.IsNullOrEmpty(config["description"]))
{
config.Remove("description");
config.Add("description", "Custom SQL Provider");
}
// Call the base class's Initialize method
base.Initialize(name, config);
} 應用程式網域。 - 接下來,實作 ValidateUser 方法。它需要輸入的使用者名稱和密碼,並驗證成員資格資料來源包含相符的使用者名稱和密碼。如果方法會傳回 true,登入 控制項可讓使用者通過驗證。 否則,它會要求認證的一次。
public override bool ValidateUser(string username, string password)
{
SqlConnection cnn = null;
SqlCommand cmd = null;
bool userExists = true;
try
{
cnn = new SqlConnection();
cnn.ConnectionString = "connection string for the existing data source";
cnn.Open();
string selectQry = "Select query for username and password";
cmd = new SqlCommand(selectQry, cnn);
SqlDataReader rdr = cmd.ExecuteReader();
if (!rdr.Read())
userExists = false;
}
catch (Exception ex)
{
throw ex;
}
finally
{
cmd.Dispose();
cnn.Close();
}
return userExists;
} - 實作一個稱為 CreateUserCreateUserWizard 控制項由呼叫的多個方法。它接受輸入使用者名稱、 密碼、 電子郵件地址及其他資訊,並將新使用者加入至現有的成員資格資料來源。它會傳回 MembershipUser 物件,表示新建立的使用者。它也會設定 MembershipCreateStatus,它會告訴使用者是否已成功建立。我們如果未成功建立使用者可以指定原因
public override MembershipUser CreateUser(string username, string
password, string email, string passwordQuestion, string
passwordAnswer, bool isApproved, object providerUserKey,
out MembershipCreateStatus status)
{
SqlConnection cnn = null;
SqlCommand cmd = null;
MembershipUser newUser = null;
try
{
cnn = new SqlConnection();
cnn.ConnectionString = "connection string for the existing data source";
cnn.Open();
string insertQry = "Prepare the Insert query...";
cmd = new SqlCommand(insertQry, cnn);
cmd.ExecuteNonQuery();
// Right now I am giving default values for DateTime
// in Membership constructor.
newUser = new MembershipUser(
"AspNetCustomMembershipProvider",
username, null, String.Empty, String.Empty,
String.Empty, true, false, DateTime.Now,
DateTime.Now, DateTime.Now, DateTime.Now,
DateTime.Now
);
status = MembershipCreateStatus.Success;
}
catch (Exception ex)
{
status = MembershipCreateStatus.ProviderError;
newUser = null;
throw ex;
}
finally
{
cmd.Dispose();
cnn.Close();
}
return newUser;
} - 其餘的方法看起來像下面所列的那些。如果您希望可以實作任何它們。
// MembershipProvider Properties
public override string ApplicationName
{
get { throw new NotSupportedException(); }
set { throw new NotSupportedException(); }
}
public override bool EnablePasswordRetrieval
{
get { return false; }
}
public override bool EnablePasswordReset
{
get { return false; }
}
public override int MaxInvalidPasswordAttempts
{
get { throw new NotSupportedException(); }
}
public override int MinRequiredNonAlphanumericCharacters
{
get { throw new NotSupportedException(); }
}
public override int MinRequiredPasswordLength
{
get { throw new NotSupportedException(); }
}
public override int PasswordAttemptWindow
{
get { throw new NotSupportedException(); }
}
public override MembershipPasswordFormat PasswordFormat
{
get { throw new NotSupportedException(); }
}
public override string PasswordStrengthRegularExpression
{
get { throw new NotSupportedException(); }
}
public override bool RequiresQuestionAndAnswer
{
get { return false; }
}
public override bool RequiresUniqueEmail
{
get { return false; }
}
public override MembershipUser GetUser(string username,
bool userIsOnline)
{
throw new NotSupportedException();
}
public override MembershipUserCollection GetAllUsers(int pageIndex,
int pageSize, out int totalRecords)
{
throw new NotSupportedException();
}
public override int GetNumberOfUsersOnline()
{
throw new NotSupportedException();
}
public override bool ChangePassword(string username,
string oldPassword, string newPassword)
{
throw new NotSupportedException();
}
public override bool
ChangePasswordQuestionAndAnswer(string username,
string password, string newPasswordQuestion,
string newPasswordAnswer)
{
throw new NotSupportedException();
}
public override bool DeleteUser(string username,
bool deleteAllRelatedData)
{
throw new NotSupportedException();
}
public override MembershipUserCollection
FindUsersByEmail(string emailToMatch, int pageIndex,
int pageSize, out int totalRecords)
{
throw new NotSupportedException();
}
public override MembershipUserCollection
FindUsersByName(string usernameToMatch, int pageIndex,
int pageSize, out int totalRecords)
{
throw new NotSupportedException();
}
public override string GetPassword(string username, string answer)
{
throw new NotSupportedException();
}
public override MembershipUser GetUser(object providerUserKey,
bool userIsOnline)
{
throw new NotSupportedException();
}
public override string GetUserNameByEmail(string email)
{
throw new NotSupportedException();
}
public override string ResetPassword(string username,
string answer)
{
throw new NotSupportedException();
}
public override bool UnlockUser(string userName)
{
throw new NotSupportedException();
}
public override void UpdateUser(MembershipUser user)
{
throw new NotSupportedException();
} - 編譯類別庫專案。它將會產生 DLL 的輸出。
- 開啟現有的網站,或建立新的 Web 站台。
- 在網站中加入 DLL 參考。
- 登錄提供者在 Web.config 檔中,如下所示。
<membership defaultProvider="AspNetCustomMembershipProvider">
<providers>
<clear />
<add name="AspNetCustomMembershipProvider" type="CustomMembershipProvider"/>
</providers>
</membership> - 新增名為的 Login.aspx 可以用 登入 控制項的 Web Form 頁面。
<form id="Form1" runat="server">
<div>
<asp:Login ID="Login1" runat="server"></asp:Login>
</div>
</form> - 新增另一個名為的 CreateUser.aspx 可以用 CreateUserWizard 控制項的 Web Form 網頁。
<form id="Form1" runat="server">
<div>
<asp:CreateUserWizard ID="CreateUserWizard1" runat="server"></asp:CreateUserWizard>
</div>
</form> - 執行這兩個 Web Form] 頁面,您會看到輸出。
如果沒有使用 Visual Studio 您可以執行下列步驟:
- 開啟 [任何文字編輯器]。
- 建立檔案,檔名為 CustomMembershipProvider.cs,],再遵循步驟 5 到 17 中給定的指示。
- 建立 [wwwroot] 資料夾下的目錄。
- 開始 Microsoft 網際網路資訊服務 (IIS) 管理員,並標記為虛擬根目錄新目錄。而且,確認它設定為萬一另一個版本的.NET Framework 安裝在電腦上,在 Microsoft.NET Framework 2.0 下執行。
- 將 Web Form 網頁和 Web.config 複製該目錄中。
- 建立新的目錄下的 [App_Code] 資料夾。
- 複製 CustomMembershipProvider.cs 檔案中 [App_Code] 資料夾。
- 從 「 IIS 管理員 」 執行 CreateUser.aspx Web Form 網頁。
結論
這是所有現在上自訂成員資格提供者。我希望本專欄將協助您了解建立自訂成員資格提供者及它們如何對使用者提供抽象概念的基本概念。
感謝您的時間。我們預期撰寫更多關於提供者所提供的 ASP.NET 2.0 與如何我們可以擴充來自訂其行為根據到我們的需求。
如需關於提供者的詳細資訊,請造訪下列網站:
如往常請隨意送出您想要在將來解決資料行的主題或使用
Ask For It
(http://support.microsoft.com/common/survey.aspx?scid=sw;en;1176&p0=&p1=&p2=&p3=&p4=)
表單的知識庫中的想法。