试图将会话变量转换为aspx中的字符串。类文件

时间:2017-04-13 15:06:31

标签: c# asp.net

string email = System.Web.HttpContext.Current.Session["email"].ToString();

我正在尝试执行类似代码ab的操作,我可以检索存储在会话中的值。我已经在我的aspx.cs文件上完成了string email = (string)(Session["email"]);,它确实向我返回了存储在会话中的电子邮件。

我现在想知道如何在类文件上完成它。

这不起作用

public int countBasketItems()
{

    int counter = 0;

    String CS = System.Configuration.ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString;
    using (SqlConnection con = new System.Data.SqlClient.SqlConnection(CS))
    {
        string email = HttpContext.Current.Session["email"].ToString();
        SqlCommand cmd = new SqlCommand("select Count(*) from basket where email = '" + email + "')", con);
        con.Open();
        counter = (int)cmd.ExecuteScalar();
    }
    return counter;

}

这有效

   public int countBasketItems()
{

    int counter = 0;
    string email="";

    String CS = System.Configuration.ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString;
    using (SqlConnection con = new System.Data.SqlClient.SqlConnection(CS))
    {
        email = (string) HttpContext.Current.Session["email"];
        SqlCommand cmd = new SqlCommand("select Count(*) from basket where email = '" + email + "'", con);
        con.Open();
        counter = (int)cmd.ExecuteScalar();
    }
    return counter;

}

1 个答案:

答案 0 :(得分:0)

您正在使用的方法应该有效。 在类文件中,确保您要导入System.web 然后在你的班级中,你现在应该能够访问HttpContext,从而访问当前的会话(httpcontext.current.session)。

我自己在Web应用程序中使用此方法而没有错误。 我有类文件使用那种确切的方法,即使在同一解决方案中交叉项目也没有错误。