angular - Angular - 无法通过 POST 请求向 ASP.NET 发送数据

我正在尝试在我的网站内建立一个身份验证系统。我正在向我的 ASP.NET 服务器发送一个简单的 POST 请求,其中包含电子邮件和密码,并且由于某种原因,服务器内的数据(电子邮件和密码)为空。我不知道我做错了什么,我是 ASP.NET 和 Angular 的初学者。

Angular 代码:(我尝试在某些元素内的文本框中显示文本,它显示了正确的文本)

isUserLoggedIn: boolean;
  emailAddress: string;
  password: string;

  constructor(private http: HttpClient, @Inject('BASE_URL') private baseUrl: string) {}

  login() {

    const headers = {'Content-Type': 'application/json', };
    const body = { emailAddress: this.emailAddress.toString, password: this.password.toString };
    this.http.post<any>(this.baseUrl + "login", body, { headers }).subscribe(result => {
      this.isUserLoggedIn = result;
      if (this.isUserLoggedIn) console.log("Logged in")
      else console.log("Not logged in")
    }, error => console.error(error));

  }

我的 ASP.NET 控制器:

[HttpPost]
[Route("login")]
public bool LoginUser(string emailAddress, string password)
{
    // DOES NOT PRINT ANY VALUE OF EMAIL OR PASSWORD
    Console.WriteLine("1: " + emailAddress);
    Console.WriteLine("2: " + password);
            
    SakilaContext context = HttpContext.RequestServices.GetService(typeof(SakilaContext)) as SakilaContext;
    return context.LoginUser(emailAddress, password);
}

我在 ASP.NET 服务器中的数据库代码:

public bool LoginUser(string emailAddress, string password)
{
    bool isUserLoggedIn = false;
    List<UserModel> list = new List<UserModel>();
    using (MySqlConnection conn = GetConnection())
    {
        string query = $"SELECT * FROM users WHERE email = '{emailAddress}'";
        conn.Open();
        MySqlCommand cmd = new MySqlCommand(query, conn);
        using (MySqlDataReader reader = cmd.ExecuteReader())
        {
            while (reader.Read())
            {
                if (reader.HasRows)
                {
                    string db_password = reader.GetString("password");
                    if (db_password == password)
                    {
                        isUserLoggedIn = true;
                    }
                }
            }
        }
    }
    return isUserLoggedIn;
}

回答1

创建一个 LoginModel 类。

public class LoginModel
{
    public string EmailAddress { get; set; }
    public string Password { get; set; }
}

更改 Login 方法签名以通过 [FromBody] 从请求正文中读取对象 value。

[HttpPost]
[Route("login")]
public bool LoginUser([FromBody] LoginModel model)
{
    Console.WriteLine(model.EmailAddress);
    Console.WriteLine(model.Password);

    ...
}

对于 Angular,我认为以下部分不正确:

const body = { emailAddress: this.emailAddress.toString, password: this.password.toString };

改成

const body = { emailAddress: this.emailAddress.toString(), password: this.password.toString() };

或者

const body = { emailAddress: this.emailAddress, password: this.password };

边注:

不要连接 SQL 命令中的 value,使用带有 https://mysqlconnector.net/overview/using-addwithvalue/ 的参数化查询。查看https://stackoverflow.com/questions/7505808/why-do-we-always-prefer-using-parameters-in-sql-statements

string query = $"SELECT * FROM users WHERE email = @emailAddress";
conn.Open();
MySqlCommand cmd = new MySqlCommand(query, conn);
cmd.Parameters.AddWithValue("@emailAddress", emailAddress);

参考

https://docs.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-6.0#frombody-attribute

相似文章

最新文章