简体   繁体   English

从我的SPA FETCH POST接收到的控制器viewmodel值为null

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

I am doing a POST back to my Asp.net Controller from my SPA. 我正在从SPA将POST回传到Asp.net控制器。 The controller has this setup: 控制器具有以下设置:

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

My asp.net Core API login viewmodel is: 我的asp.net Core API登录视图模型是:

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

My SPA is written in Typescript. 我的SPA用Typescript编写。

My SPA interface is: 我的SPA界面是:

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

and I declare it as such: 我这样声明:

private login: userLogin,

and my FETCH is structured so: 我的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"
    }

NOTE: When set up in POSTMAN this works. 注意:在POSTMAN中设置时,此方法有效。

Looking at those console logs: 查看那些控制台日志:

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

Here is the network tab in Chrome showing the payload: 这是Chrome中的网络标签,其中显示了有效负载:

在此处输入图片说明

Finally here is the controller paused at a break showing the values for the POST being null and null: 最终,控制器暂停了一下,显示POST的值为null和null:

在此处输入图片说明

Why am I getting null on the fetch POST? 为什么我在获取POST时得到空值? What do I need to do to make my API receive the values? 我需要做什么才能使我的API接收值?

You are explicitly specifying the contentType as application/json and sending the json stringified version of the object. 您将contentType明确指定为application/json并发送该对象的json字符串化版本。 This will be send the data in the request body when the asynchronous call is made. 进行异步调用时,这将在请求正文中发送数据。 So you need to use FromBody attribute so that the the framework know how to do model binding properly from the request which contains your js object/data in json format. 因此,您需要使用FromBody属性,以便框架知道如何从包含json格式的js对象/数据的请求中正确进行模型绑定。

Change the decorator attribute from FromForm to FromBody 将装饰器属性从FromForm更改为FromBody

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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