【问题标题】:Sessions and Cookies Retrieving first and last name Welcome msg会话和 Cookie 检索名字和姓氏欢迎消息
【发布时间】:2014-09-15 08:55:37
【问题描述】:

试图在这个程序上工作,理论上它应该将名字和姓氏都检索到“欢迎”lblMessage。在 ASP.NET 中使用 Cookie。

IS所做的只是检索 ["FirstName"]。我需要两者

Order.aspx.cs

  protected void Page_Load(object sender, EventArgs e){

  string firstName = (string)Session["FirstName"];
    string lastName = (string)Session["LastName"];
    if ((firstName != null) && (lastName != null))
    {
        lblWelcome.Text = "Welcome back, " + (string)Session["FirstName"] + (string)Session[" LastName"] + "!";
    }

}

CheckOut.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
    // get entry data from cookies
    //if (Request.Cookies["FirstName"] != null)
    //    txtFirstName.Text = Request.Cookies["FirstName"].Value;
    //if (Request.Cookies["LastName"] != null)
    //    txtLastName.Text = Request.Cookies["LastName"].Value;

    //get entry data from session state
    if (!IsPostBack)
    {
        string firstName = (string)Session["FirstName"];
        if (firstName != null) txtFirstName.Text = (string)Session["FirstName"];
        string lastName = (string)Session["LastName"];
        if (lastName != null) txtLastName.Text = (string)Session["LastName"];
        txtFirstName.Focus();
    }
}

private void LoadCustomerData()
{
    Session["FirstName"] = txtFirstName.Text;
    Session["LastName"] = txtLastName.Text;  
}

在几个部分 [w/o 显示整个代码] 这是我迄今为止所拥有的。

想知道是否有人可以用一双新的眼光来看看我做错了什么?

【问题讨论】:

    标签: c# asp.net session cookies


    【解决方案1】:

    最有可能的候选人将是一个错字,如果不查看所有代码就很难发现。我建议删除“魔术字符串”(即Session["FirstName"])并为会话变量名称声明一些常量:

    [in some static class]
    public const string FirstNameKey = "FirstName";
    public const string LastNameKey = "LastName";
    

    然后一致地引用这些键:

    Session[FirstNameKey] = txtFirstName.Text;
    

    我实际上通常使用 GUID 作为名称(例如 public const string FirstNameKey = "49b63214-1812-4ba3-9ace-ae423c682d7c";,这样就不会在应用程序中重复它们

    【讨论】:

      【解决方案2】:

      问题在于 cookie 名称中的类型:Session[" LastName"]

      代替

      string firstName = (string)Session["FirstName"]; ... = (string)Session["FirstName];

      使用

      string firstName = (string)Session["FirstName"]; ... = firstName;

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-08-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-02
        相关资源
        最近更新 更多