导航

ASP.NET 2.0 中Profile的学习心得

Posted on 2009-12-10 16:27  敬云  阅读(377)  评论(0)    收藏  举报
简单的说,Profile使用用户唯一标识并为每一个用户保存其对应信息的一个工具
它是 HttpContext 的一个属性,其具体的继承关系,底层实现,在此不提。
其配置使用如下:

首先允许匿名用户
在web.config配置文件中找到‘
<system.web>
 <anonymousIdentification enabled="true" />
然后再
<system.web>
    <profile>节点
尝试加入
      <properties>
           <add name="Myusername" type="string" allowAnonymous="true" />
      </properties>
保存web.config后会发现在 .aspx.cs 文件中会出现 this.Profile.Myusername 属性,类型为string
再尝试
      <properties>
           <add name="Myusername" type="string"  allowAnonymous="true"/>
           <add name="Myuserage" type="int"  allowAnonymous="true"/>
      </properties>
保存web.config后会在Profile属性中出现 int 类型的 Myuserage
继续扩展
加入个复杂的类型怎么样
创建一个实体User类,命名空间Entity,项目中User类的完整路径为 Entity.User
cs文件中代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Entity
{
    public class User
    {
        private string userID = "";
        private string userPwd = "";

        public string UserID
        {
            get { return userID; }
            set { userID = value; }
        }
        public string UserPwd
        {
            get { return userPwd; }
            set { userPwd = value; }
        }
    }
}
完成之后在web.config中
尝试
      <properties>
           <add name="Myusername" type="string" />
           <add name="Myuserage" type="int" />
           <add name="User" type = "Entity.User" >
      </properties>
结果 this.Profile.User 成为我们所想要的User类的实体
我们可以通过 this.Profile.User.UserID 保存或提取用户的ID

继续深入会发现  <group>节点也是一个好帮手
     <properties>
           <add name="Myusername" type="string"  allowAnonymous="true"/>
           <add name="Myuserage" type="int"  allowAnonymous="true"/>
           <add name="User" type = "Entity.User"  allowAnonymous="true">
           <group name="group1">
                   <add name="Myusername" type="string" allowAnonymous="true" />
                   <add name="User" type="Entity.User"  allowAnonymous="true"/>
          </group>  
      </properties>
这样之后我们可以对属性进行分组,从而更加有条理的管理我们的属性

创建完我们所用的用户属性后,就是保存数据的问题了
 ASP.NET 将每个不同用户的数据保存在哪里,实际上 Profile 会自动将数据通过 SQLExpress (保证你的SQLExpress开着)保存在App_Data目录下
通过每一个用户的唯一标识来区分,当用户重新登录时也可以根据他的唯一标识来提取已保存的数据
从而获得它的信息,购物车就是很成功的例子

学习笔记仅供参考,若果有错误,欢迎指出,以待互相促进