ASP.NET Profiles are a very useful tool for persisting user data. Most other methods of state management do not easily persist the data across user visits, but Profiles plug seamlessly into the ASP.NET Membership database to provide a convenient persistent store.
Defining Profile Properties
The first step to using Profiles is to defining them in the web.config file. This is done by adding the
<profile> section to the web.config file and the adding each property using a
<add> element nested inside the
In addition to name the
<add> element accepts several attributes which should be used. By default the format of the Profile is set to String but can be set to any datatype, for example the above JoinedDate profile should have a attribute of type added with the associated data type:
<add name="JoinedDate" type="System.DateTime" />
defaultValue is another useful attribute which sets the default of the Profile. For example, this could be used the set the initial language a user’s preferences is set to:
<add name="Language" defaultValue="en" />
There are several additional attributes, namely:
- serializeAs : The format to use for serializing this Profile (String, CML, Binary, or ProviderSpecific)
- readOnly : This is a boolean which sets if the Profile can be updated.
- allowAnonymous : A boolean which sets if the Profile can be used with anonymous profiles.
- provider : The profile provider that is used to manage this property.
Profile access is very simple. Just use Profile.ProfileName anywhere in an app to get the profile value for the user. For example:
String langStr = Profile.Language
Updating ASP.NET Profiles is also a simple procedure, just assign the value to the Profile and it will be stored:
Profile.Language = langTxtBox.Text
Note that the Profile will not actually be written to the database (and therefore not stored) until the page life-cycle is complete. Therefore after updating a Profile, avoid accessing it unless the page has finished processing (as only the old value will be stored).
Be aware that Profiles do not come without issues. There is a performance cost to using Profiles inappropriately see ASP.NET Profile Performance for more details.