简体   繁体   中英

The parameterized query @..SELECT ' expects the parameter '@EmpUsername', which was not supplied

I try to write login authentication ASP.NET API core 3.1 and React but my code can't log in successfully.

string SqlQuery = @"SELECT * FROM dbo.EmpUser WHERE EmpUsername = @EmpUsername and EmpPassword = @EmpPassword;";

using (SqlCommand sqlCommand = new SqlCommand(SqlQuery, _sqlConnection))
{
    sqlCommand.CommandType = System.Data.CommandType.Text;
    sqlCommand.CommandTimeout = 180;

    sqlCommand.Parameters.AddWithValue("@EmpUsername", request.EmpUsername);
    sqlCommand.Parameters.AddWithValue("@EmpPassword", request.EmpPassword);

    using (DbDataReader dataReader = await sqlCommand.ExecuteReaderAsync())
    { 
        if (dataReader.HasRows)
        {
            response.Message = dataReader.HasRows.ToString();
        }
        else
        {
            response.IsSuccess = false;
            response.Message = "Login unsuccessful";
            return response;
        }
    }
}

Message from console.log is:

The parameterized query '(@EmpUsername nvarchar(4000),@EmpPassword nvarchar(4000))SELECT ' expects the parameter '@EmpUsername', which was not supplied.

When I edit my code to:

sqlCommand.Parameters.AddWithValue("@EmpUsername", (request.EmpUsername== null ? "" : request.EmpUsername));
sqlCommand.Parameters.AddWithValue("@EmpPassword", (request.EmpPassword == null ? "" : request.EmpPassword));

The message from console.log is

Login unsuccessful

If you were previously getting an error message telling you that the parameter wasn't supplied then that means that the value was null . You've now changed your code so that, if that value is null , you supply an empty string. Why would you expect to be able to log in with an empty string as the username?

If the value is null then there's obviously a problem elsewhere, so you need to find and fix that. Possibly the user isn't actually providing any input, in which case you shouldn't even be trying to log in. Possibly there's an issue passing the user input from the UI. We can't tell from what you've provided but the code you have shown us is working as it should, ie if the username is empty then the login should fail.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM