控制器视图模型值从我的 SPA FETCH POST 接收为 null

Controller viewmodel values are received as null from my SPA FETCH POST

我正在 POST 从我的 SPA 返回到我的 Asp.net 控制器。控制器具有此设置:

    [HttpPost]
    [AllowAnonymous]
    public async Task<IActionResult> Get([FromForm] LoginViewModel model)
    {

我的 asp.net 核心 API 登录视图模型是:

public class LoginViewModel
{
    public string Username { get; set; }
    public string Password { get; set; }
}

我的 SPA 是用 Typescript 写的。

我的 SPA 界面是:

interface userLogin {
  Username: string;
  Password: string;
}

我这样声明:

private login: userLogin,

我的 FETCH 结构如下:

 // Lets do a fetch!

  console.log("username, password: ", this.username, this.password);

  this.login.Username = this.username;
  this.login.Password = this.password;

  console.log("login.username, login.password", this.login);
  console.log("JSON login: ", JSON.stringify(this.login));

  const task = fetch("/api/jwt", {
    method: "POST",
    body: JSON.stringify(this.login),
    headers: {
      "Content-Type": "application/json;charset=UTF-8"
    }

注意:在 POSTMAN 中设置时有效。

查看那些控制台日志:

username, password: admin password
login.ts:37 login.username, login.password {Username: "admin", Password: "password"}
login.ts:38 JSON login:  {Username: "admin", Password: "password"}

这是 Chrome 中的网络选项卡,显示了有效载荷:

最后,控制器暂停显示 POST 的值为 null 和 null:

为什么我在获取 POST 时得到空值?我需要做什么才能让我的 API 收到这些值?

您将 contentType 明确指定为 application/json 并发送对象的 json 字符串化版本。这将在进行异步调用时发送请求正文中的数据。因此,您需要使用 FromBody 属性,以便框架知道如何从包含 json 格式的 js object/data 的请求中正确进行模型绑定。

将装饰器属性从 FromForm 更改为 FromBody

[HttpPost]
[AllowAnonymous]
public async Task<IActionResult> Get([FromBody] LoginViewModel model)
{
    // to do : Return something
}