首页 > 解决方案 > 未设置对象引用

问题描述

public static Boolean ValidateUser(string struser, string strpass)
{
    // Establish connection information
    SqlConnection conn_string = new   SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Data Source=137.145.169.3;Initial Catalog=SICI4266;Persist Security Info=True;User ID=SICI4266G3;Password=*******"].ConnectionString);
    // Establish SQL command
    SqlCommand sql_comm = new SqlCommand("SELECT count(userID) FROM HIEPA.HIEPA_USERS where UserName = @usuario and UserPassword = @contrasena ; ", conn_string);
    // Provide Parameter values
    sql_comm.Parameters.AddWithValue("@usuario", struser);
    sql_comm.Parameters.AddWithValue("@contrasena", strpass);
    // Open the connection
    conn_string.Open();
    // Execute the SQL command and assign the resulting value to an integer variable
    Int32 intUserCount = Convert.ToInt32(sql_comm.ExecuteScalar());
    // Close the connection
    conn_string.Close();
    // Evaluate the integer variable content; greater than cero is a valid combination
    if (intUserCount == 1)
    {
        return true;
    }
    else
    {
        return false;
    }
}

有人能告诉我为什么会提示这个错误吗?

在此处输入图像描述

标签: c#asp.net

解决方案


异常结果中以红色突出显示的行中的这个表达式是null

System.Configuration.ConfigurationManager.ConnectionStrings["Data Source=137.145.169.3;Initial Catalog=SICI4266;Persist Security Info=True;User ID=SICI4266G3;Password=*******"]

它为空,因为该Connection[]属性需要字符串的名称,而不是完整的字符串。它正在尝试在集合中查找字符串,没有找到那么大的长文本块,因此返回null

鉴于上述情况,您然后尝试引用引用的.Connection字符串属性null。就好像你已经这样做了:

null.ConnectionString;

要么更改该代码以使用文件中列出的连接字符串的名称web.config,要么因为您已经拥有整个字符串,所以只需将该字符串直接提供给SqlConnection()构造函数。无论哪种方式,该代码都应该清理一些:

//comments should focus on "why", rather than "what"
public static Boolean ValidateUser(string struser, string strpass)
{
    using (var conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["conn string name"].ConnectionString))
    using (var sql_comm = new SqlCommand(""SELECT count(userID) FROM HIEPA.HIEPA_USERS where UserName = @usuario and UserPassword = @contrasena ; ", conn))
    {
        //Don't use AddWithValue(). It forces ADO.Net to guess about parameter types.
        //Use exact column types and lengths instead
        sql_comm.Parameters.Add("@usuario", SqlDbType.NVarChar, 50).Value = struser;
        //Dear God, please tell me you're not using a plain-text password? That's a HUGE mistake!
        sql_comm.Parameters.Add("@contrasena", SqlDbType.NVarChar, 180).Value = strpass;

        conn.Open();
        return (1 == (int)sql_comm.ExecuteScalar());
    }
}

推荐阅读