如何在asp中使用会话变量使用c#

Ada*_*ngh 4 asp.net

我们如何用c#在asp .net的登录页面创建会话给我充分的例子......

Kar*_*oll 18

假设您的代码在页面中(内联或后面的代码),您可以使用...

DataType someValue = (DataType)Session["SessionVariableNameHere"]; //Getter
Session["SessionVariableNameHere"] = someNewValue; //Setter
Run Code Online (Sandbox Code Playgroud)

显然,您需要正确命名会话变量,并在将其从会话中恢复时转换为适当的数据类型.

编辑 - 一个完整的例子

protected void Login1_LoggedIn(object sender, EventArgs e)
{
    Session["LoginTime"] = DateTime.Now;
}
Run Code Online (Sandbox Code Playgroud)

然后在页面加载...

protected void Page_Load(object sender, EventArgs e)
{
    Literal1.Text = "Last Online: " + ((DateTime)Session["LoginTime"]).ToString("yyyy-MM-dd");
}
Run Code Online (Sandbox Code Playgroud)


Ulh*_*ano 5

当用户输入正确的用户名和密码时。创建一个将持有标志的会话

if(userLoggedInSuccessfully)
{
          Session["SessionVariableName"] = "Flag";
}
Run Code Online (Sandbox Code Playgroud)

如果您在页面中使用母版页,只需检查 page_load

page_load()
{
                 if(Session["SessionVariableName"] != null)
                 {
                       if(Session["SessionVariableName"]=="Flag")
                       {
                              //Valid User
                       }
                       else
                       {
                                  //Invalid user
                       }
                 }
                 else
                 {
                           //Session expired
                 }

}
Run Code Online (Sandbox Code Playgroud)