Asp.net 如何在具有存储过程的会话中存储主键

Asp.net 如何在具有存储过程的会话中存储主键,asp.net,Asp.net,我有一个使用了存储过程的登录页面。我正在使用会话来存储作为主键的用户id。当我输入错误的用户名和密码时,它应该重定向到其他页面,但它给了我一个例外,即“对象引用未设置为对象的实例”。我的login.aspx.cs代码是: SqlCommand cmd1 = new SqlCommand("select artistId from artist where Username=@username and Artistpass=@password",con); cmd1.Parameters.AddW

我有一个使用了存储过程的登录页面。我正在使用会话来存储作为主键的用户id。当我输入错误的用户名和密码时,它应该重定向到其他页面,但它给了我一个例外,即“对象引用未设置为对象的实例”。我的login.aspx.cs代码是:

SqlCommand cmd1 = new SqlCommand("select artistId from artist where Username=@username and Artistpass=@password",con);
cmd1.Parameters.AddWithValue("@username", txtusr.Text);
        cmd1.Parameters.AddWithValue("@password", txtpass.Text);
        con.Close();
         Session["username"] = txtusr.Text;
        SqlParameter param = new SqlParameter("@username", txtusr.Text.Trim());
        SqlParameter param1 = new SqlParameter("@password", txtpass.Text.Trim());
        SqlCommand cmd = new SqlCommand("login", con);
        cmd.Parameters.Add(param);
        cmd.Parameters.Add(param1);
        cmd.CommandType = CommandType.StoredProcedure;
        con.Open();
        SqlDataReader dr = cmd.ExecuteReader();
        if (dr.Read())
        {
            Response.Redirect("afterlogin.aspx");
        }
        else
        {
            MessageBox.Show("Login Unsuccessful");

        }
        con.Close();
        if (con.State != ConnectionState.Open)
        {
            con.Open();
        }
        int id = (int)cmd1.ExecuteScalar();
        Session["ID"] = id;
        con.Close();
plz帮助。

如果where语句未找到与用户和密码匹配的内容,则返回null

因此不能将null返回值强制转换为整数

    object id = cmd1.ExecuteScalar();
    Session["ID"] = id;
    con.Close();

当然,这意味着您需要检查重定向页面中的Session[“ID”]变量,以查看它是否为null

哪一行代码导致了错误?Bzz
MessageBox.Show
在ASP.net中??cmd1.ExecuteScalar-在哪里声明了cmd1?我在int-ID=(int)cmd1.ExecuteScalar()处出错;你甚至不需要写所有这些东西,看看Asp.net的身份,除非你真的知道你在做什么,否则你可能会做更多的工作和更多的安全漏洞。这段代码表明您正在以纯文本形式存储密码,这是一个非常糟糕的主意。