【问题标题】:Session doesnt exist in current context?当前上下文中不存在会话?
【发布时间】:2011-07-19 21:21:01
【问题描述】:

在尝试实现会话时遇到问题,它说它在当前上下文中不存在,我错过了什么吗?

 protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
    {
        //database connection string
        OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite; User=x; Password=x; OPTION=3;");
        cn.Open();
        OdbcCommand cmd = new OdbcCommand("Select * from User where username=? and password=?", cn);
        DataSet ds = new DataSet();
        //Select the username and password from mysql database 

        cmd.Parameters.Add("@username", OdbcType.VarChar);
        cmd.Parameters["@username"].Value = this.Login1.UserName;

        cmd.Parameters.Add("@password", OdbcType.VarChar);
        cmd.Parameters["@password"].Value = this.Login1.Password;
        //use asp login control to check username and password

        //Session["UserID"] = "usrName";
        //set the UserID from the User Table unsure how to add this to the sql syntax above

        OdbcDataReader dr = default(OdbcDataReader);
        // Initialise a reader to read the rows from the login table.  
        // If row exists, the login is successful  

        dr = cmd.ExecuteReader();
        DataTable dt = ds.Tables[0];
        DataRow dp = dt.Rows[0];

        OdbcDataAdapter adp = new OdbcDataAdapter(cmd)
        { 
        DataTable dt = new DataTable(); 
        adp.Fill(dt); 
        if (dt.Rows.Count != 0) 
        { 
            Session("UserID") = Convert.ToString(dt.Rows[0]["UserID"]);
            e.Authenticated = true; 
            Response.Redirect("UserProfileWall.aspx"); 
        } 
    } 

【问题讨论】:

    标签: c# asp.net mysql sql html


    【解决方案1】:

    应该是

    Session["UserID"] = Convert.ToString(dp["UserID"]);
    

    你需要使用方括号

    【讨论】:

    • 哈哈,我看到了。您可能会争辩说 dp["UserID"].ToString() 更正确
    • 我可以,但我没那么挑剔。
    【解决方案2】:

    我认为您似乎将Session 对象作为一种方法来访问。您需要:

    Session["UserID"] = dp["UserID"].ToString();
    

    【讨论】:

    • 我如何在另一个 aspx 页面上检索这个?
    • @Garrith Graham:如果您的意思是在完成此操作后如何访问另一个网页中的会话变量,您将使用:if(Session["UserID"] != null) { string userID = Session["UserID"].ToString(); }
    • @Garrith 您需要使用 OdbcDataAdapter 来填充您的数据表。试试这个:使用 (OdbcDataAdapter adp = new OdbcDataAdapter(cmd)) { DataTable dt = new DataTable(); adp.填充(dt); if (dt.Rows.Count != 0) { Session("UserID") = Convert.ToString(dt.Rows[0]["UserID"]); e.Authenticated = true; Response.Redirect("UserProfileWall.aspx"); } }
    • 抱歉,hopdizzle 你能把它作为答案发布吗?我遇到了一些错误?
    猜你喜欢
    • 2011-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-13
    • 1970-01-01
    • 2023-03-30
    • 2019-08-05
    相关资源
    最近更新 更多