快速回顾
1.允许匿名需要设置哪些东西
1. <authentication mode="Forms" />
2.<anonymousIdentification enabled="true"/>
3.<profile automaticSaveEnabled="true" enabled="true">
<properties>
<group name="grpUserName">
<add name="UserName" allowAnonymous="true" type="String" serializeAs="Binary"/>
</group>
</properties>
</profile>
2.匿名购物车如何实现:即当用户admin登陆的时候,匿名选的购物车会自动加到admin的购物车
1.Web.config配置里再加一个组,其中type="ShoppingCart"对应一个类
<group name="grpShoppingCart">
<add name="MyCart" allowAnonymous="true" type="ShoppingCart" serializeAs="Binary"/>
</group>
2.Global.asax代码Profile_OnMigrateAnonymous
3.基本的购物车功能:
1.点AddToCart将该行数据添加到购物车(Profile里的MyCart.items,而且可以是匿名的)
2.购物车要和Profile里的集合MyCart.items绑定
1.分为2步:允许匿名用户,和匿名用户的购物车在登陆的时候保存
1.允许匿名用户
1.新建一个网站,右键网站添加新项(Web.config),设置3个地方
2 . < anonymousIdentification enabled = " true " />
3 . < profile automaticSaveEnabled = " true " enabled = " true " >
< properties >
< group name = " grpUserName " >
< add name = " UserName " allowAnonymous = " true " type = " String " serializeAs = " Binary " />
</ group >
</ properties >
</ profile >
2.在页面Default.aspx里拖一个Label,在页面的Load事件里写如下代码后,保存运行,看到匿名Id
else {lbl_AnonUser.Text = "" ;}
2.允许匿名购物:即当用户admin登陆的时候,匿名选的购物车会自动加到admin的购物车
条件:需要有数据库,购物车,会员用户,需要一个方法将匿名购物车加到登陆用户购物车里
1.数据库(添加一个NorthWind,并在Web.config里配置好连接字符串)
2.购物车:在App_Code里加CartItem和ShoppingCart 2个类,并声明[Serializable]特性
[Serializable]
public class CartItem
{
public CartItem()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
public CartItem(string itemName,decimal itemPrice,int count)
{
this.ItemName = itemName;
this.ItemPrice = itemPrice;
this.Count = count;
}
private string itemName;
public string ItemName
{
get { return itemName; }
set { itemName = value; }
}
private decimal itemPrice;
public decimal ItemPrice
{
get { return itemPrice; }
set { itemPrice = value; }
}
private int count;
public int Count
{
get { return count; }
set { count = value; }
}
}
[Serializable]
public class ShoppingCart
{
public ShoppingCart()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
private List<CartItem> items = new List<CartItem>();
public List<CartItem> Items
{
get { return items; }
set { items = value; }
}
}
3.会员用户:用Asp.net配置创建用户,这样系统会自动创建一个数据库AspNetSqlProfileProvider
然后配置好Web.config,profile的defaultProvider不设置会默认AspNetSqlProfileProvider数据库
点Visual Studio解决方案最右边的Asp.Net配置-->选 安全-->点 创建用户(密码要大于7位并有个特殊字符,如!@#¥%……&*,比如我设置的密码:admin@admin) 完成后就可以关闭页面了
<?xml version="1.0"?>
<!--
注意: 除了手动编辑此文件以外,您还可以使用
Web 管理工具来配置应用程序的设置。可以使用 Visual Studio 中的
“网站”->“Asp.Net 配置”选项。
设置和注释的完整列表在
machine.config.comments 中,该文件通常位于
\Windows\Microsoft.Net\Framework\v2.x\Config 中
-->
<configuration>
<appSettings/>
<connectionStrings>
<add name="NorthwindCNConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\NorthwindCN.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
<system.web>
<!--
设置 compilation debug="true" 将调试符号插入
已编译的页面中。但由于这会
影响性能,因此只在开发过程中将此值
设置为 true。
-->
<compilation debug="true">
<assemblies>
<add assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/></assemblies></compilation>
<!--
通过 <authentication> 节可以配置 ASP.NET 使用的
安全身份验证模式,
以标识传入的用户。
-->
<authentication mode="Forms">
<forms defaultUrl="Default.aspx" loginUrl="Default.aspx"/>
</authentication>
<anonymousIdentification enabled="true"/>
<profile automaticSaveEnabled="true" enabled="true">
<properties>
<group name="grpUserName">
<add name="UserName" allowAnonymous="true" type="String" serializeAs="Binary"/>
<add name="PassWord" allowAnonymous="true" type="String" serializeAs="Binary"/>
<add name="Email" allowAnonymous="true" type="String" serializeAs="Binary"/>
</group>
<group name="grpShoppingCart">
<add name="MyCart" allowAnonymous="true" type="ShoppingCart" serializeAs="Binary"/>
</group>
</properties>
</profile>
<!--
如果在执行请求的过程中出现未处理的错误,
则通过 <customErrors> 节可以配置相应的处理步骤。具体说来,
开发人员通过该节可以配置
要显示的 html 错误页
以代替错误堆栈跟踪。
<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
<error statusCode="403" redirect="NoAccess.htm" />
<error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>
-->
</system.web>
</configuration>
4.转移购物车的方法,在Global.asax里(右键WebUI,新建全局应用程序)写Profile_OnMigrateAnonymous
需要在最上面导入命名空间<%@ Import Namespace="System.Web.Profile" %>
<%@ Application Language="C#" %>
<%@ Import Namespace="System.Web.Profile" %>
<script runat="server">
void Application_Start(object sender, EventArgs e)
{
// 在应用程序启动时运行的代码
}
void Application_End(object sender, EventArgs e)
{
// 在应用程序关闭时运行的代码
}
void Application_Error(object sender, EventArgs e)
{
// 在出现未处理的错误时运行的代码
}
void Session_Start(object sender, EventArgs e)
{
// 在新会话启动时运行的代码
}
void Session_End(object sender, EventArgs e)
{
// 在会话结束时运行的代码。
// 注意: 只有在 Web.config 文件中的 sessionstate 模式设置为
// InProc 时,才会引发 Session_End 事件。如果会话模式设置为 StateServer
// 或 SQLServer,则不会引发该事件。
}
void Profile_OnMigrateAnonymous(object sender, ProfileMigrateEventArgs e)
{
// get the profile for the anonymous user
ProfileCommon anonProfile = Profile.GetProfile(e.AnonymousID);
// if they have a shopping cart, then migrate that to the authenticated user
if (anonProfile.grpShoppingCart.MyCart != null)
{
if (Profile.grpShoppingCart.MyCart == null)
Profile.grpShoppingCart.MyCart = new ShoppingCart();
Profile.grpShoppingCart.MyCart.Items.AddRange(anonProfile.grpShoppingCart.MyCart.Items);
anonProfile.grpShoppingCart.MyCart = null;
}
ProfileManager.DeleteProfile(e.AnonymousID);
AnonymousIdentificationModule.ClearAnonymousIdentifier();
}
</script>
5.最后实现Default页面,页面的界面和后台
1.界面中的用户名和登陆(是工具箱-->登陆(拖LoginName和LoginStatus))
2.选购下面的GridView1是直接拖一张Product表进来的
3.购物车下面的GridView2的数据是在后台绑定的,然后在点右边小三角(点 添加新列)
-->选ButtonField,把文本改为删除
4.下面的登陆控件(是工具箱-->登陆(拖Login))
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;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Profile.IsAnonymous)
{
lbl_AnonUser.Text = Profile.UserName;
}
else
{
lbl_AnonUser.Text = "";
}
}
protected void GridView2_PreRender(object sender, EventArgs e)
{
GridView2.DataSource = Profile.grpShoppingCart.MyCart.Items;
GridView2.DataBind();
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
int productId = Convert.ToInt32(((GridViewRow)((LinkButton)sender).Parent.Parent).Cells[0].Text);
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["NorthwindCNConnectionString"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = string.Format("SELECT * FROM [Product] WHERE [ProductId] = {0}", productId);
SqlDataReader dr = cmd.ExecuteReader();
CartItem item = null;
if (dr.Read())
{
item = new CartItem();
item.ItemName = dr["ProductName"].ToString();
item.ItemPrice = Convert.ToInt32(dr["Price"]);
}
dr.Close();
con.Close();
bool flag = false;
foreach (CartItem cartItem in Profile.grpShoppingCart.MyCart.Items)
{
if (cartItem.ItemName == item.ItemName)
{
flag = true;
cartItem.Count++;
break;
}
}
if (flag == false)
{
CartItem cartItem = new CartItem(item.ItemName, item.ItemPrice, 1);
Profile.grpShoppingCart.MyCart.Items.Add(cartItem);
}
}
protected void GridView2_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
Profile.grpShoppingCart.MyCart.Items.RemoveAt(e.RowIndex);
}
}
6.代码 下载