ASP.NET 2.0揭秘读书笔记七——使用用户配置文件Profile

     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;

posted on 2009-05-08 08:38  边写边唱  阅读(382)  评论(0编辑  收藏  举报

导航