繁体   English   中英

asp.net 中的 Cookies 和 session

[英]Cookies and session in asp.net

我正在使用此代码创建登录名并将用户详细信息存储在 cookie 中

if (ValidateUser(txtUserName.Value,txtUserPass.Value) )
{
   //string useremail = Convert.ToString(txtUserName.Value);
   Session.Add("useremail", txtUserName.Value);
   FormsAuthenticationTicket tkt;
   string cookiestr;
   HttpCookie ck;
   tkt = new FormsAuthenticationTicket(1, txtUserName.Value, DateTime.Now, 
     DateTime.Now.AddMinutes(30), chkPersistCookie.Checked, "your custom data");
   cookiestr = FormsAuthentication.Encrypt(tkt);
   ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);
   if (chkPersistCookie.Checked)
     ck.Expires=tkt.Expiration; 
   ck.Path = FormsAuthentication.FormsCookiePath; 
   Response.Cookies.Add(ck);
}

我也在创建一个 session Session.Add("useremail", txtUserName.Value); 成功验证后,它被重定向到 user.aspx 我想读取 user.aspx 页面中的 useremail 值,但是当我尝试访问用户页面中的值时,它没有显示 useremail 字段。

protected void Page_Load(object sender, EventArgs e)
    {
        if
            (Session["useremail"] == null) Response.Redirect("Home.aspx");
        else

            BindGridView(useremail);
    }

这是我的网络配置:

<authentication mode="Forms"><forms name=".YAFNET_Authentication" loginUrl="Home.aspx" protection="All" timeout="43200" cookieless="UseCookies"/></authentication>

如果我做错了什么,请纠正我。 还请告诉我如何将 useremail 值传递给 user.aspx 页面,以便我可以将该值传递给 gridview function

您可以像这样将 object 添加到 session state 中:

Session["useremail"] = "john.smith@microsoft.com";

然后,您可以通过以下方式检索它:

var useremail = Session["useremail"] ?? null;
if (useremail == null)
{
   //...
}
else
{
    BindGridView(useremail);
}

如果 session state 中不存在“useremail”项,则 useremail 变量将设置为 null 否则它将包含电子邮件地址。

只需将其更改为

protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["useremail"] == null)
            Response.Redirect("Home.aspx");
        else
            BindGridView((string)Session["useremail"]);
    }

您对身份验证 session state 和 cookies 之间的关系感到困惑。 In ASP.NET, Session State and Forms Authentication are not linked ie their scope are different. 对于未经身份验证的用户,您可以拥有一些 session state。 Session 和 forms 身份验证使用不同的 cookies 进行跟踪,并且 cookie 管理或多或少是自动的,您不需要像以前那样编写代码来管理它。 此外,您存储在 cookie 中的内容与 session state 中的内容无关。 也可以同时拥有 session 和 forms 身份验证,以便在没有 cookies 的情况下工作。 所以下面的代码应该适用于 session state

Session["key"] = "put your data here";

// retrieve the data elsewhere
var data = Session["key"];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM