ASP.NET 2.0 Framework提供了一種不用於cookie和Session狀態的方式儲存使用者資訊:Profile對象。Profile提供強型別、可持久化的Session狀態表單。
可以在應用程式的根Web設定檔定義一組Profile屬性來建立Profile。ASP.NET Framework 在後台動態編譯一個包含這些屬性的類。
<?xml version="1.0"?>
<configuration>
<system.web>
<profile>
<properties>
<add name="firstName" />
<add name="lastName" />
<add name="numberOfVisits" type="Int32" defaultValue="0" />
</properties>
</profile>
</system.web>
</configuration>
當定義Profile屬性時,可以使用下面的屬性:
• Name——用於指定屬性的名稱;
• Type——指定屬性的類型,預設是字串類型;
• defaultValue——指定屬性預設值;
• readOnly ——是否屬性唯讀;
• serializeAs——用於指定一個屬性如何持久化為靜態持久化資料;
• allowAnonymous ——是否允許匿名使用者讀寫屬性;
• provider——用於關聯屬性到特定的Profile提供者;
• customProviderData ——用於傳遞自訂的資料到Profile提供者。
理解Profile是持久化的很重要,如果應用程式為一個使用者佈建了Profile屬性,那麼即使這個使用者一直沒有回到網站,網站也會為其保留Profile屬性值。
Profile對象使用提供者模型,預設的Profile提供者是SqlProfileProvider.預設情況下,該提供者儲存Profile資料到名為ASPNETDB.mdf的SQL Server 2005 Express資料庫中,資料庫儲存在應用程式的App_Code檔案夾。如果資料庫不存在,第一次使用Profile對象時它會被自動建立。
建立使用者設定檔組
如果需要定義很多的Profile屬性,則將這些Profile屬性分成組更易管理,如下所示:
<?xml version="1.0"?>
<configuration>
<system.web>
<profile>
<properties>
<group name="Preferences">
<add name="BackColor" defaultValue="lightblue"/>
<add name="Font" defaultValue="Arial"/>
</group>
<group name="ContactInfo">
<add name="Email" defaultValue="Your Email"/>
<add name="Phone" defaultValue="Your Phone"/>
</group>
</properties>
</profile>
</system.web>
</configuration>
在代碼中使用:
lblEmail.Text = Profile.ContactInfo.Email;
lblPhone.Text = Profile.ContactInfo.Phone;