文章編號: 910440 - 上次校閱: 2007年11月22日 - 版次: 1.4

藉由建立自訂成員資格提供者在 ASP.NET 2.0 中使用現有的資料來源登入控制項

系統提示本文適用於您使用的作業系統之外的作業系統。與您不相關的文章內容已停用。
ASP.NET 支援語音資料行

藉由建立自訂成員資格提供者在 ASP.NET 2.0 中使用現有的資料來源登入控制項

若要自訂您的需要此資料行的 我們想要邀請您送出您的想法,有關您感興趣的主題,而且在將來知識庫文件和支援語音資料行,處理您想要查看的問題。您可以送出您的想法和使用 Ask For It (http://support.microsoft.com/common/survey.aspx?scid=sw;en;1176&p0=&p1=&p2=&p3=&p4=) 表單的意見反應。另外還有連結至表單底部的 這個資料行。

在此頁中

全部展開 | 全部摺疊

簡介

哈,歡迎後 !我的名稱是 Parag Agarwal,我在這裡支援工程師在 Microsoft。本月份我們要討論另一個很棒的功能,在 Microsoft ASP.NET 2.0 管理登入控制項的提供者。

概觀

在本月的專欄中,我將探討下列主題:
  • 登入控制項的簡短概觀
  • 提供者模型在 ASP.NET 中的簡要概觀 2.0
  • 逐步解說上建立自訂提供者可使用的登入控制項與現有的資料來源

登入控制項

這是很常見的需求,以在幾乎每一個 Web 應用程式中有登入功能。發行 ASP.NET 2.0 之前我們使用設計來驗證使用者的使用者介面 (UI)。這牽涉到撰寫許多多餘的程式碼。若要避免這個問題,ASP.NET 2.0 提供需要沒有程式設計的 Web 應用程式完成登入解決方案一大堆伺服器控制項的形式。在內部,這些控制項負責呈現適當的 UI,使用者可以輸入他或她的認證,並驗證它們。現在,我們不必設計網頁開發人員為使用者介面,而且我們不需要小心的驗證使用者藉由撰寫我們自己的程式碼。登入 控制項所使用的基礎提供者模型會負責的。我們將會看到 登入 控制項來驗證使用者在下一節中的使用之提供者的方式。您可以找到登入控制項和我們如何可以使用它們在下列網站的相關資訊:
http://msdn2.microsoft.com/en-us/library/ms178329.aspx (http://msdn2.microsoft.com/en-us/library/ms178329.aspx)

提供者模型

提供者模型可讓開發人員建置隨插即用軟體。 它基本上被為了提高從實作的抽象概念,讓這兩個部分可以獨立有所不同。若要執行此動作 ASP.NET 提供有所有抽象方法和屬性提供實作這些方法和屬性在衍生類別所實作所需特定抽象基底類別。

如需有關抽象的基底類別的詳細資訊,請造訪下列網站:
http://msdn2.microsoft.com/en-us/library/k535acbf(vs.71).aspx (http://msdn2.microsoft.com/en-us/library/k535acbf(vs.71).aspx)
所以,來彙總,提供者會為媒介由控制項使用與資料存放區進行互動。它們會提供應用程式與資料來源之間的抽象概念的裝置驅動程式提供抽象從硬體裝置的方式相同。

因為我們將討論關於成員資格提供者的此發行項] 談什麼類別 ASP.NET 2.0 提供成員資格功能。ASP.NET 2.0 成員資格功能會定義稱為 MembershipProvider 類別的抽象基底類別。此外,MembershipProvider 衍生自不同的基底類別稱為 ProviderBase 類別是一般類別到所有提供者。因此,開發人員可以衍生現有 MembershipProvider 類別來建立自己的提供者類別。

如需有關 MembershipProviderProviderBase 類別的詳細資訊,請造訪下列網站:
http://msdn2.microsoft.com/en-us/library/system.web.security.membershipprovider.aspx (http://msdn2.microsoft.com/en-us/library/system.web.security.membershipprovider.aspx)

http://msdn2.microsoft.com/en-us/library/system.configuration.provider.providerbase.aspx (http://msdn2.microsoft.com/en-us/library/system.configuration.provider.providerbase.aspx)
一旦我們已定義成員資格提供者,必須描述在組態檔中所有的 Web 應用程式) 的 Machine.config 或特定的 Web 應用程式) 的 Web.config 中。適當的提供者會從由 ASP.NET 組態檔中所提供的資訊的執行階段具現化。但是,它有可能在執行的階段以動態方式變更提供者。

如需有關指定成員資格提供者的組態設定的詳細資訊,請造訪下列網站:
http://msdn2.microsoft.com/en-us/library/ms178329.aspx (http://msdn2.microsoft.com/en-us/library/ms178329.aspx)
現在,請 登入 控制項隨附使用特定的資料配置/資料結構的兩個內建的成員資格提供者: 不過,如果我們想要使用現有的資料庫結構,我們很容易可以程式碼以取得舊的資料庫結構和說話的登入控制項的自訂成員資格提供者。

建立自訂成員資格提供者

既然我們有足夠的資訊登入控制項和基礎他們使用的提供者模型上,讓我們來建立自訂成員資格提供者以取得現有的登入控制項工時與自訂資料存放區。

附註自訂提供者會使用稱為 TestDB 的 SQL Server 資料庫。TestDB 會有命名為具有欄位使用者識別碼的 使用者、 使用者名稱,以及密碼和電子郵件識別碼] 和 [地址等其他資訊的資料表。
  1. 啟動 Microsoft Visual Studio 2005。
  2. 建立類別庫專案,並賦予一個的名稱,例如 CustomMembershipProviderLib。
  3. 將原始程式檔加入至專案,例如 CustomMembershipProvider.cs。
  4. 在 [參考] 區段中包含 System.WebSystem.Configuration
  5. 確認下列命名空間都包含在 [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;
  6. 繼承 CustomMembershipProvider 類別與 MembershipProvider class.
    class CustomMembershipProvider : 
    MembershipProvider
  7. 我們已經知道所以屋 MembershipProvider 是估算因此我們需要覆寫 CustomMembershipProvider 類別中的所有抽象方法抽象的類別。會自動的 Visual Studio 2005 中沒有很酷的功能。當您延伸任何抽象類別,只在 抽象類別 上, 按一下滑鼠右鍵,然後再按 [實作抽象類別。這會自動將放所有抽象方法的宣告。您會注意到每個方法主體包含常見一行程式碼。
    throw new Exception("The method or operation is not implemented.");
    這表示自訂提供者支援哪些功能。

    附註初始化 方法的實作是強制的。
  8. 自訂提供者中我們將會專注於提供一些功能,如下所示:
    • 藉由使用 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);
    }
    應用程式網域。
  9. 接下來,實作 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;
    }
  10. 實作一個稱為 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;
    }
  11. 其餘的方法看起來像下面所列的那些。如果您希望可以實作任何它們。
    // 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();
    }
  12. 編譯類別庫專案。它將會產生 DLL 的輸出。
  13. 開啟現有的網站,或建立新的 Web 站台。
  14. 在網站中加入 DLL 參考。
  15. 登錄提供者在 Web.config 檔中,如下所示。
    <membership defaultProvider="AspNetCustomMembershipProvider">
      <providers>
        <clear />
        <add  name="AspNetCustomMembershipProvider"	type="CustomMembershipProvider"/>
      </providers>
    </membership>
  16. 新增名為的 Login.aspx 可以用 登入 控制項的 Web Form 頁面。
    <form id="Form1" runat="server">
      <div>
        <asp:Login ID="Login1" runat="server"></asp:Login>
      </div>
    </form>
  17. 新增另一個名為的 CreateUser.aspx 可以用 CreateUserWizard 控制項的 Web Form 網頁。
    <form id="Form1" runat="server">
      <div>
        <asp:CreateUserWizard ID="CreateUserWizard1" runat="server"></asp:CreateUserWizard>
      </div>
    </form>
  18. 執行這兩個 Web Form] 頁面,您會看到輸出。
如果沒有使用 Visual Studio 您可以執行下列步驟:
  1. 開啟 [任何文字編輯器]。
  2. 建立檔案,檔名為 CustomMembershipProvider.cs,],再遵循步驟 5 到 17 中給定的指示。
  3. 建立 [wwwroot] 資料夾下的目錄。
  4. 開始 Microsoft 網際網路資訊服務 (IIS) 管理員,並標記為虛擬根目錄新目錄。而且,確認它設定為萬一另一個版本的.NET Framework 安裝在電腦上,在 Microsoft.NET Framework 2.0 下執行。
  5. 將 Web Form 網頁和 Web.config 複製該目錄中。
  6. 建立新的目錄下的 [App_Code] 資料夾。
  7. 複製 CustomMembershipProvider.cs 檔案中 [App_Code] 資料夾。
  8. 從 「 IIS 管理員 」 執行 CreateUser.aspx Web Form 網頁。

結論

這是所有現在上自訂成員資格提供者。我希望本專欄將協助您了解建立自訂成員資格提供者及它們如何對使用者提供抽象概念的基本概念。

感謝您的時間。我們預期撰寫更多關於提供者所提供的 ASP.NET 2.0 與如何我們可以擴充來自訂其行為根據到我們的需求。

如需關於提供者的詳細資訊,請造訪下列網站:
提供者工具組
http://msdn2.microsoft.com/en-us/asp.net/aa336558.aspx (http://msdn2.microsoft.com/en-us/asp.net/aa336558.aspx)

提供者模型的設計模式和規格,第 1 部分
http://msdn2.microsoft.com/en-us/library/ms972319.aspx (http://msdn2.microsoft.com/en-us/library/ms972319.aspx)

提供者設計模式第 2 部分
http://msdn2.microsoft.com/en-us/library/ms972370.aspx (http://msdn2.microsoft.com/en-us/library/ms972370.aspx)
如往常請隨意送出您想要在將來解決資料行的主題或使用 Ask For It (http://support.microsoft.com/common/survey.aspx?scid=sw;en;1176&p0=&p1=&p2=&p3=&p4=) 表單的知識庫中的想法。

這篇文章中的資訊適用於:
  • Microsoft ASP.NET 2.0
關鍵字:?
kbmt kbprogramming kbsecurity kbcode kbhowto KB910440 KbMtzh
機器翻譯機器翻譯
重要:本文是以 Microsoft 機器翻譯軟體翻譯而成,而非使用人工翻譯而成。Microsoft 同時提供使用者人工翻譯及機器翻譯兩個版本的文章,讓使用者可以依其使用語言使用知識庫中的所有文章。但是,機器翻譯的文章可能不盡完美。這些文章中也可能出現拼字、語意或文法上的錯誤,就像外國人在使用本國語言時可能發生的錯誤。Microsoft 不為內容的翻譯錯誤或客戶對該內容的使用所產生的任何錯誤或損害負責。Microsoft也同時將不斷地就機器翻譯軟體進行更新。
按一下這裡查看此文章的英文版本:910440? (http://support.microsoft.com/kb/910440/en-us/ )
Microsoft及(或)其供應商不就任何在本伺服器上發表的文字資料及其相關圖表資訊的恰當性作任何承諾。所有文字資料及其相關圖表均以「現狀」供應,不負任何擔保責任。Microsoft及(或)其供應商謹此聲明,不負任何對與此資訊有關之擔保責任,包括關於適售性、適用於某一特定用途、權利或不侵權的明示或默示擔保責任。Microsoft及(或)其供應商無論如何不對因或與使用本伺服器上資訊或與資訊的實行有關而引起的契約、過失或其他侵權行為之訴訟中的特別的、間接的、衍生性的損害或任何因使用而喪失所導致的之損害、資料或利潤負任何責任。
Retired KB Article依現狀不再更新的知識庫內容免責聲明
本文旨在說明 Microsoft 不再提供支援的產品。因此,本文係依「現狀」提供,不會再更新。