Profile小试

  在做购物车时有到两种方案CookieSession,各有优缺点,于是上网搜了一下,发现有以前没听说过的Profile,甚感好奇,也没管是否实用,花两天功夫看了看。因为VS2010SQL SERVER出了问题,也懒得去管,所以没法用内嵌,也就只体验在外部连接的情况。

  因为要自动生成表,所以在开发之前要先配置一下。首先c:\Windows\Microsoft.NET\ Framework\v4.0.30319\aspnet_regsql.exe运行一下(v4.0.30319视不同.NET版版待定),在选择默认数据库时,选择你已经建好的数据库。

1.WebSite中的Profile

1)配置文件

<connectionStrings>
<add name="petshop" connectionString="server=.;database=MyPetShop;uid=sa;pwd=123"/>
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.0"/>
<authentication mode="Forms"/>
<anonymousIdentification enabled="true"/>
<profile defaultProvider="myProFileProvider">
      <providers>
        <add name="myProFileProvider" type="System.Web.Profile.SqlProfileProvider"
 connectionStringName="petshop"/>
      </providers>
<properties>
<add name="num" type="Int32" serializeAs="Xml" allowAnonymous="true"/>
</properties>
</profile>
</system.web>
其中<add name="num" type="Int32" serializeAs="Xml" allowAnonymous="true"/>的serializeAs代表在数据库中存放的数据形式还可选为字符串、二进制等。这一句的作用是在用户访问时,.NET会new出一个对象来,名为num,允许匿名。

2)在后台就可以这样来操作了 

   protected void Page_Load(object sender, EventArgs e)
    {
        Response.Write(Profile.num++);
    }

这样在访问后会在数据库自动生成很多表,其中有一个是profile,可以看到,每一个用户访问,会在该表中新建条数据。(同一台电脑,不同浏览器也认为是不同用户)

2.在WebApplicatio中的Profile

WebApplication中使用Profile就要相对麻烦一点,以至于有些人认为不能用。

首先配置文件相同,其次如果要将自己定义的类型对象存入数据库,就需要在自定义类前加[Serializable],且配置文件的<add name="num" type="Int32" serializeAs="Xml" allowAnonymous="true"/>要改为serializeAs="Binary",在后台类中也不能像WebSite中直接用Profile点出来,而是先HttpContext context = HttpContext.Current;再context.Profile.GetPropertyValue("..."),这时拿到的是object的还要自己转换一下


参考资料:使用ASP.NET 2.0 Profile存储用户信息[翻译] Level 200


warn
作者:心亦
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
原文地址:https://www.cnblogs.com/szhx/p/3219354.html