ASP.NET 2.0 內建會員、角色與設定檔提供者,開箱即用。但當業務需求超越預設功能——如儲存至非 SQL Server、整合舊有資料結構、跨應用程式共享設定檔——自訂提供者成為關鍵。本文詳細說明設定檔提供者架構、自訂實作步驟,並搭配身分驗證與授權機制說明。
ProfileProvider 定義讀寫合約,內建 SqlProfileProvider 為預設實作。web.config <profile> 區段宣告屬性名稱、型別、預設值、是否匿名使用。ProfileModule.MigrateAnonymous 事件合併資料。<profile defaultProvider="CustomProfileProvider">
<properties>
<add name="FirstName" type="String" />
<add name="LastName" type="String" />
<add name="BirthDate" type="DateTime" />
<add name="Preferences" type="System.Collections.Specialized.StringCollection" serializeAs="Xml" />
<add name="Theme" type="String" defaultValue="Blue" allowAnonymous="true" />
</properties>
<providers>
<add name="CustomProfileProvider"
type="MyApp.Providers.CustomProfileProvider, MyApp"
connectionStringName="AppDb"
applicationName="/" />
</providers>
</profile>
ProfileProvider 抽象類別。GetPropertyValues:從資料源讀取屬性值,填入 SettingsPropertyValueCollection。SetPropertyValues:將集合寫回資料源。DeleteProfiles、DeleteInactiveProfiles:清理機制。FindProfilesByUserName、GetAllProfiles:管理查詢(可選)。SettingsPropertyValue.SerializeAs 指明 String、Xml、Binary、ProviderSpecific 四種模式,自訂提供者需對應處理。設定檔常與會員系統搭配:
MembershipProvider 驗證帳密、管理帳戶狀態。RoleProvider 實作角色型授權 ([Authorize(Roles="Admin")])。ProfileProvider 儲存個人化資料(偏好、購物車、草稿)。三者共用 applicationName 可跨應用程式共享使用者資料。
enableAnonymousIdentification 追蹤匿名用戶。automaticSaveEnabled="false",手動呼叫 Profile.Save() 減少資料庫往返。ProfileEventArgs 事件,記錄異常與效能指標。自訂設定檔提供者讓 ASP.NET 2.0 的個人化框架脫離預設綁定,適應企業級異構儲存、跨系統整合等複雜場景。掌握提供者模式,更能舉一反三應用於會員、角色、Session、快取等內建服務的擴展。