2017-11-03 99 views
0

我正在从我的SPA进行回发到我的Asp.net控制器的POST。该控制器具有这种设置:控制器视图模型值从我的SPA FETCH POST收到为空

[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是写在打字稿。

我的SPA接口:

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

和我宣布它是这样:

private login: userLogin, 

和我的抓取结构如此:

// 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" 
    } 

注:在设置邮递员这工作。

寻找那些控制台日志:

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网络标签表示有效载荷:

enter image description here

最后这里在控制器暂停在表示的值的破POST为空且为空:

enter image description here

为什么我在抓取POST上得到空值?我需要做些什么来使我的API接收这些值?

回答

1

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

变化从FromForm装饰属性FromBody

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

是奏效的感谢。所以我假设任何时候我会对我的api进行POST,我的控制器必须有“FromBody”? – si2030

相关问题