首页 > 解决方案 > 使用 (SqlDataReader reader = cmd.ExecuteReader()) 错误 asp.net mvc5

问题描述

即使我检查过并且我的数据库中确实有此参数,我也会收到此错误:

参数化查询“(@UserName nvarchar(4000))SELECT Email AS Email FROM AspNetUsers”需要参数“@UserName”,但未提供该参数。

这是在我的 AccountController 中:

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> SendConfirmationMail() // resend confirmation link in case the users haven't received it 
{
    string res = null;
    string connection = GetConnectionString("DefaultConnection");
    using (SqlConnection myConnection = new SqlConnection(connection))

    {
        myConnection.Open();
        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "SELECT Email AS Email FROM AspNetUsers WHERE UserName = @UserName";
        cmd.Connection = myConnection;
        cmd.Parameters.AddWithValue("@UserName", EConfUser);

        using (SqlDataReader reader = cmd.ExecuteReader())
        {
            if (reader.HasRows)
            {
                if (reader.Read())
                {
                    res = reader["Email"].ToString(); // get user's email from db
                    var user = await UserManager.FindByEmailAsync(res); // find applicationuser user by email
                                                                        //update user's email link date
                    UpdateEmailLinkDate(EConfUser);
                    // generate email conf token and send it
                    codeType = "EmailConfirmation";
                    await SendEmail("ConfirmEmail", "Account", user, res, "WelcomeEmail", "Confirm your account");
                }
                myConnection.Close();
            }
        }
    }
    return RedirectToAction("ConfirmationEmailSent", "Account");
}

我将不胜感激任何帮助。

标签: asp.net-mvc-5

解决方案


尝试这个:

cmd.Parameters.Add("@UserName", SqlDbType.VarChar).Value = EConfUser ?? 
(object)DBNull.Value;

推荐阅读