实现匿名用户向注册用户迁移

来源:互联网 发布:神州数码医疗 知乎 编辑:程序博客网 时间:2024/05/16 12:23

 Global.asax

<%@ Application Language="C#" %>

<script runat="server">
   
    void Profile_MigrateAnonymous(Object sender, ProfileMigrateEventArgs pe)
    {
        ProfileCommon anonProfile = Profile.GetProfile(pe.AnonymousID);
        if (anonProfile.ShoppingCart.Total != 0)
        {
            Profile.ShoppingCart = anonProfile.ShoppingCart;
        }

        Membership.DeleteUser(pe.AnonymousID);

        ProfileManager.DeleteProfile(pe.AnonymousID);

        AnonymousIdentificationModule.ClearAnonymousIdentifier();
    }

</script>

 

web.config

<connectionStrings>
  <add name="NorthwindConnectionString" connectionString="Data Source=b764e28a5fe449f/helen;Initial Catalog=Northwind;Integrated Security=True" providerName="System.Data.SqlClient"/>
 </connectionStrings>
 <system.web>
  <!--
            设置 compilation debug="true" 将调试符号插入
            已编译的页面中。但由于这会
            影响性能,因此只在开发过程中将此值
            设置为 true。
        -->
  <compilation debug="true"/>
  <!--
            通过 <authentication> 节可以配置 ASP.NET 使用的
            安全身份验证模式,
            以标识传入的用户。
        -->
  <anonymousIdentification enabled="true"/>
  <profile>
   <properties>
    <add name="ShoppingCart" type="ShoppingCart" serializeAs="Binary" allowAnonymous="true"/>
   </properties>
  </profile>
  <authentication mode="Forms">
   <forms loginUrl="Login.aspx"></forms>
  </authentication>

</system.web>

 

default.aspx

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>无标题页</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <fieldset style="width: 620px">
                <legend class="mainTitle">实现匿名用户向注册用户迁移</legend>
                <table border="0" cellpadding="5" width="620px">
                    <tr>
                        <td style="font-size:small;">当前用户是:<asp:Label ID="lbUserName" runat="server"></asp:Label>                      
                        </td>
                        <td>
                        <asp:LinkButton ID="lbtLogin" runat="server" CssClass="littleTitle" OnClick="lbtLogin_Click">登录</asp:LinkButton>
                            <asp:LinkButton ID="lbtLogout" runat="server" CssClass="littleTitle" OnClick="lbtLogout_Click">退出</asp:LinkButton></td>                       
                    </tr>
                    <tr>
                        <td colspan="2"><hr />
                        </td>
                    </tr>
                    <tr align="center">
                        <td>
                            <p class="littleTitle">
                                待售商品列表</p>
                        </td>
                        <td>
                            <p class="littleTitle">
                                购物车</p>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
                                SelectCommand="SELECT [ProductID], [ProductName], [UnitPrice] FROM [Products]"></asp:SqlDataSource>
                            <asp:GridView ID="ProductGrid" runat="server" OnSelectedIndexChanged="AddCartItem"
                                Width="300px" AllowPaging="True" AutoGenerateColumns="False" BackColor="White"
                                BorderColor="#CC9966" BorderStyle="None" BorderWidth="1px" CellPadding="4" DataKeyNames="ProductID"
                                DataSourceID="SqlDataSource1" Font-Size="Small" PageSize="5">
                                <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
                                <RowStyle BackColor="White" ForeColor="#330099" />
                                <Columns>
                                    <asp:CommandField ButtonType="Image" SelectImageUrl="~/Images/button_buy.gif" ShowSelectButton="True" />
                                    <asp:BoundField DataField="ProductName" HeaderText="商品名称" SortExpression="ProductName" />
                                    <asp:BoundField DataField="UnitPrice" DataFormatString="{0:c}" HeaderText="单价" SortExpression="UnitPrice" />
                                </Columns>
                                <PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
                                <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
                                <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
                            </asp:GridView>
                        </td>
                        <td valign="top">
                            <asp:GridView ID="CartGrid" AutoGenerateColumns="False" DataKeyNames="ID" OnSelectedIndexChanged="RemoveCartItem"
                                CellPadding="4" Width="320px" runat="Server" BackColor="White" BorderColor="#CC9966"
                                BorderStyle="None" BorderWidth="1px" Font-Size="Small">
                                <Columns>
                                    <asp:ButtonField CommandName="select" Text="Remove" ButtonType="Image" ImageUrl="~/Images/button_del.gif" />
                                    <asp:BoundField DataField="Name" HeaderText="商品名称" />
                                    <asp:BoundField DataField="Price" HeaderText="单价" DataFormatString="{0:c}" />
                                    <asp:BoundField DataField="Quantity" HeaderText="数量" />
                                </Columns>
                                <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
                                <RowStyle BackColor="White" ForeColor="#330099" />
                                <PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
                                <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
                                <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
                            </asp:GridView>
                            <asp:Label ID="lblTotal" runat="Server" CssClass="littleTitle" /></td>
                    </tr>                   
                </table>
            </fieldset>
        </div>
    </form>
</body>
</html>

.cs

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 (!Page.IsPostBack)
        {
            BindShoppingCart();
        }
    }
    // 显示Profile对象中保存的购物车信息
    protected void BindShoppingCart()
    {
        //如果Profile中存储的购物车的商品不为空,则进行数据绑定并计算总价
        if (Profile.ShoppingCart != null)
        {
            CartGrid.DataSource = Profile.ShoppingCart.CartItems;
            CartGrid.DataBind();
            lblTotal.Text = "总价:" + Profile.ShoppingCart.Total.ToString("c");
        }
    }
    // 将选中商品添加到购物车中
    protected void AddCartItem(object sender, EventArgs e)
    {
        // 获取被选中数据行
        GridViewRow row = ProductGrid.SelectedRow;
        // 获取主键ID的值
        int ID = (int)ProductGrid.SelectedDataKey.Value;
        // 获取商品名称
        String Name = row.Cells[1].Text;
        // 获取商品单价
        decimal Price = Decimal.Parse(row.Cells[2].Text, System.Globalization.NumberStyles.Currency);
        // 如果Profile中存储的购物车对象为null,则创建一个相应对象
        if (Profile.ShoppingCart == null)
        {
            Profile.ShoppingCart = new ShoppingCart();
        }
        // 利用前面获取的数据,在Profile对象购物车中添加被选中的商品
        Profile.ShoppingCart.AddItem(ID, Name, Price);
        // 显示购物车数据
        BindShoppingCart();
    }
    // 将选中商品从购物车中删除
    protected void RemoveCartItem(object sender, EventArgs e)
    {
        // 获取被选中商品的主键ID
        int ID = (int)CartGrid.SelectedDataKey.Value;
        // 利用ID,从Profile对象购物车中删除该商品
        Profile.ShoppingCart.RemoveItem(ID);
        // 显示购物车数据
        BindShoppingCart();
    }

    protected void Page_PreRender(object sender, EventArgs e)
    {
        if (Profile.IsAnonymous)
        {
            lbUserName.Text = "匿名用户";
            lbtLogout.Visible = false;
        }
        else
        {
            lbUserName.Text = Profile.UserName;
            lbtLogin.Visible = false;
        }
    }
    protected void lbtLogin_Click(object sender, EventArgs e)
    {
        Response.Redirect("Login.aspx");
    }
    protected void lbtLogout_Click(object sender, EventArgs e)
    {
        FormsAuthentication.SignOut();
    }
}

原创粉丝点击