Profile 在中文版的MSDN中被稱為 配置文件屬性,這個功能是在 ASP.NET 2.0 中引入的。
ASP.NET提供這個功能主要是為了簡化與用戶相關(guān)的個性化信息的讀寫方式。
簡化主要體現(xiàn)在3個方面:
1. 自動與某個用戶關(guān)聯(lián),已登錄用戶或者未登錄都支持。
2. 不需要我們設(shè)計用戶的個性化信息的保存表結(jié)構(gòu),只要修改配置文件就夠了。
3. 不需要我們實(shí)現(xiàn)數(shù)據(jù)的加載與保存邏輯,ASP.NET框架替我們實(shí)現(xiàn)好了。
為了使用Profile,我們首先在web.config中定義所需要的用戶個性化信息:
<profile> <properties> <add name="Address"/> <add name="Tel"/> </properties> </profile>
然后,就可以在頁面中使用了:
為什么會這樣呢?
原因是ASP.NET已經(jīng)根據(jù)web.config為我們創(chuàng)建了一個新類型:
using System; using System.Web.Profile; public class ProfileCommon : ProfileBase { public ProfileCommon(); public virtual string Address { get; set; } public virtual string Tel { get; set; } public virtual ProfileCommon GetProfile(string username); }
有了這個類型后,當(dāng)我們訪問HttpContext.Profile屬性時,ASP.NET會創(chuàng)建一個ProfileCommon的實(shí)例。 也正是由于Profile的強(qiáng)類型機(jī)制,在使用Profile時才會有智能提示功能。
如果我們希望為未登錄的匿名用戶也提供這種支持,需要將配置修改成:
<profile> <properties> <add name="Address" allowAnonymous="true" /> <add name="Tel" allowAnonymous="true"/> </properties> </profile> <anonymousIdentification enabled="true" />
Profile中的每個屬性還允許指定類型和默認(rèn)值,以及序列化方式,因此,擴(kuò)展性還是比較好的。
盡管Profile看上去很美,然而,使用Profile的人卻很少。
比如我就不用它,我也沒見有人有過它。
為什么會這樣?
我個人認(rèn)為:它與MemberShip一樣,是個雞肋。
通常說來,我們會為用戶信息創(chuàng)建一張User表,增加用戶信息時,會通過增加字段的方式解決。
我認(rèn)為這樣集中的數(shù)據(jù)才會更好,而不是說,有一部分?jǐn)?shù)據(jù)由我維護(hù),另一部分?jǐn)?shù)據(jù)由ASP.NET維護(hù)。
另一個特例是:我們根本不創(chuàng)建User表,直接使用MemberShip,那么Profile用來保存MemberShip沒有信息是有必要的。
還是給Profile做個總結(jié)吧:
優(yōu)點(diǎn):使用簡單。
缺點(diǎn):不實(shí)用。