在Parameters.AddWithValue中使用操作符



我试图在Parameters.AddWithValue中使用operator作为我的登录表单,但它抛出了username must be not null错误,我应该如何在Parameters.AddWithValue中使用操作符?这是我最近的工作:

public JsonResult Loginzxc(string email, string username, string password)
{
using (SqlConnection con = new SqlConnection(constring))
{
string status;
string user_type;
string reg_no;
string access = "select reg_no, username, status, user_type, password from accounts " +
"union select reg_no, username, status, user_type, password from admin_accounts where username = @user or email = @email";
string pass1;
//if(username == null)
//{
//    return Json("wrong_username");
//} else
if(password == null)
{
return Json("wrong_password");
}
pass1 = ComputeSha256Hash(password);
using (SqlCommand com = new SqlCommand(access, con))
{
com.Parameters.AddWithValue("@user", username); //Trying to merge @email and username
com.Parameters.AddWithValue("@email", email); //Trying to merge @email and username
com.CommandTimeout = 60;
SqlDataReader rreader;
using(con)
{
con.Open();
rreader = com.ExecuteReader();
if(rreader.HasRows == true)
{
while(rreader.Read())
{
string pass2 = rreader["password"].ToString();
status = rreader["status"].ToString();
user_type = rreader["user_type"].ToString();
reg_no = rreader["reg_no"].ToString();
if(user_type == "0")
{
user_type = "ADMIN";
} else if(user_type == "1")
{
user_type = "MEMBER";
}
if(pass2 != pass1)
{
return Json("wrong_password");
}
if (status == "INACTIVE")
{
return Json("INACTIVE");
}
else if (status == "BLOCKED")
{
return Json("BLOCKED");
} else if(status == "ACTIVE")
{
HttpContext.Session.SetString("username", username);
HttpContext.Session.SetString("reg_no", reg_no);
HttpContext.Session.SetString("user_type", user_type);
if (user_type == "ADMIN")
{
return Json(new { redirectUrl = Url.Action("Index", "Admin", new { id = "DSA" + reg_no }) });
} else if(user_type == "MEMBER")
{
return Json(new { redirectUrl = Url.Action("Index", "Home", new { id = "DSA" + reg_no }) });
}
} else
{
return Json("error");
}
}
}
con.Close();
}
ViewBag.notfound = "login";
return Json("no record");
}
}
// return Json("");
}

如果您试图将空值转换为空字符串,请尝试:

com.Parameters.AddWithValue("@user", username ?? string.Empty); //Trying to merge @email and username
com.Parameters.AddWithValue("@email", email ?? string.Empty); //Trying to merge @email and username

??是空合并操作符,它接受它找到的第一个非空值。它也可以像variable1 ?? variable2 ?? "bob"一样链接起来,它将返回"bob"如果前面两个变量为空

我忘记使用if else语句将null设置为""

if (username == null)
{
username = "";
} else if (email == null) {
email = "";
} else if (password == null)
{
return Json("wrong_password");
}

最新更新