ASP.NET 个性化
网站是为用户的重复访问而设计的。个性化允许网站记住用户身份和其他信息细节,并为每个用户提供个性化的环境。
ASP.NET 提供个性化网站的服务,以满足特定客户的品味和偏好。
了解配置文件
ASP.NET 个性化服务基于用户配置文件。用户配置文件定义了站点需要的用户信息类型。例如,姓名、年龄、地址、出生日期和电话号码。
此信息在应用程序的 web.config 文件中定义,ASP.NET 运行时读取并使用它。这项工作由个性化提供商完成。
从用户数据获得的用户配置文件存储在 ASP.NET 创建的默认数据库中。你可以创建自己的数据库来存储配置文件。配置文件数据定义存储在配置文件 web.config 中。
例子
让我们创建一个示例站点,我们希望我们的应用程序记住用户详细信息,如姓名、地址、出生日期等。在
<configuration> <system.web> <profile> <properties> <add name="Name" type ="String"/> <add name="Birthday" type ="System.DateTime"/> <group name="Address"> <add name="Street"/> <add name="City"/> <add name="State"/> <add name="Zipcode"/> </group> </properties> </profile> </system.web> </configuration>
在 web.config 文件中定义配置文件时,可以通过在当前 HttpContext 中找到的 Profile 属性使用该配置文件,也可以通过页面使用该配置文件。
添加文本框以获取配置文件中定义的用户输入,并添加一个用于提交数据的按钮:
更新 Page_load 以显示配置文件信息:
using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!this.IsPostBack) { ProfileCommon pc=this.Profile.GetProfile(Profile.UserName); if (pc != null) { this.txtname.Text = pc.Name; this.txtaddr.Text = pc.Address.Street; this.txtcity.Text = pc.Address.City; this.txtstate.Text = pc.Address.State; this.txtzip.Text = pc.Address.Zipcode; this.Calendar1.SelectedDate = pc.Birthday; } } } }
为提交按钮编写以下处理程序,用于将用户数据保存到配置文件中:
protected void btnsubmit_Click(object sender, EventArgs e) { ProfileCommon pc=this.Profile.GetProfile(Profile.UserName); if (pc != null) { pc.Name = this.txtname.Text; pc.Address.Street = this.txtaddr.Text; pc.Address.City = this.txtcity.Text; pc.Address.State = this.txtstate.Text; pc.Address.Zipcode = this.txtzip.Text; pc.Birthday = this.Calendar1.SelectedDate; pc.Save(); } }
第一次执行页面时,用户需要输入信息。但是,下次将自动加载用户详细信息。
元素的属性
除了我们使用的名称和类型属性外,
属性 | 描述 |
---|---|
name | 属性的名称。 |
type | 默认情况下,类型是字符串,但它允许任何完全限定的类名作为数据类型。 |
序列化 | 序列化此值时使用的格式。 |
readOnly | 只读配置文件值不能更改,默认情况下此属性为 false。 |
默认值 | 如果配置文件不存在或没有信息,则使用默认值。 |
允许匿名 | 一个布尔值,指示此属性是否可以与匿名配置文件一起使用。 |
Provider | 应用于仅管理此属性的配置文件提供程序。 |
匿名个性化
匿名个性化允许用户在识别自己之前对网站进行个性化。例如,Amazon.com 允许用户在登录之前将商品添加到购物车中。要启用此功能,可以将 web.config 文件配置为:
<anonymousIdentification enabled ="true" cookieName=".ASPXANONYMOUSUSER" cookieTimeout="120000" cookiePath="/" cookieRequiresSSL="false" cookieSlidingExpiration="true" cookieprotection="Encryption" coolieless="UseDeviceProfile"/>