ASP.Net教程

ASP.NET 个性化

网站是为用户的重复访问而设计的。个性化允许网站记住用户身份和其他信息细节,并为每个用户呈现个性化的环境。
ASP.NET 提供个性化网站的服务,以满足特定客户的品味和偏好。

了解个人资料

ASP.NET 个性化服务基于用户配置文件。用户配置文件定义了站点需要的有关用户的信息类型。例如,姓名、年龄、地址、出生日期和电话号码。
此信息在应用程序的 web.config 文件中定义,ASP.NET 运行时读取并使用它。这项工作由个性化提供商完成。
从用户数据中获取的用户配置文件存储在由 ASP.NET 创建的默认数据库中。您可以创建自己的数据库来存储配置文件。配置文件数据定义存储在配置文件 web.config 中。

示例

让我们创建一个示例站点,我们希望应用程序在其中记住用户详细信息,例如姓名、地址、出生日期等。在 <system.web> 元素内的 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 属性之外, 元素还有其他属性。下表说明了其中一些属性:
属性 说明
name 属性名称。
type 默认类型是字符串,但它允许任何完全限定的类名作为数据类型。
serializeAs 序列化此值时使用的格式。
readOnly 只读配置文件值无法更改,默认情况下此属性为 false。
defaultValue 在配置文件不存在或没有信息时使用的默认值。
allowAnonymous 一个布尔值,指示此属性是否可用于匿名配置文件。
Provider 应该用于管理此属性的配置文件提供程序。

匿名个性化

匿名个性化允许用户在识别自己之前对网站进行个性化。例如,Amazon.com 允许用户在登录之前将商品添加到购物车中。要启用此功能,可以将 web.config 文件配置为:
<anonymousIdentification enabled ="true" cookieName=".ASPXANONYMOUSUSER"
   cookieTimeout="120000" cookiePath="/" cookieRequiresSSL="false"
   cookieSlidingExpiration="true" cookieprotection="Encryption"
   coolieless="UseDeviceProfile"/>
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4