【问题标题】:Web Api paramater passed through Angular is null通过 Angular 传递的 Web Api 参数为空
【发布时间】:2018-08-15 22:16:31
【问题描述】:

所以我试图通过 Angular 服务中的 put 调用将字符串传递给我的 Web Api。服务实际上是调用Web Api端的方法,但是参数总是通过null来的。有人能解释一下吗,谢谢。

代码如下:

Web Api:(断点设置在第一个括号上)

public void Put([FromBody]string userId)
{


} 

角度:

 UpdateManagerEmail(userId){
    userId = '577f1e6e-146d-49f1-a354-b31349e7cb49';
    const headers = new HttpHeaders();
    headers.append('Content-Type', 'application/json');

    this._http.put('http://localhost:428/api/User', {
        userId : userId
    }).subscribe(returnVal => {
      console.log('returned');
    });
  }

【问题讨论】:

  • 您是否在开发者工具的网络选项卡中看到您的请求中发送的参数?
  • 我可以在请求负载中看到它
  • 你试过删除 [FromBody] 吗?
  • 没有FromBody,它不会被调用
  • 你试过用引号包裹字符串吗? this._http.put('http://localhost:428/api/User', '"' + userId + '"') 或设置变量 var data = userId 并将数据传递给 put 方法? this._http.put('http://localhost:428/api/User', data)

标签: .net angular


【解决方案1】:

为了让您的后端在您发送的请求正文中找到 userId,它必须是其中唯一的值。您应该将content-type 更改为:application/x-www-form-urlencoded; charset=UTF-8 并在没有密钥的情况下发送数据。

文档备注:

在发送简单类型之前,请考虑将值包装在复杂类型中。这为您提供了在服务器端进行模型验证的好处,并且可以在需要时更轻松地扩展您的模型。

来源:Sending simple types

另外,this blog 解释得比我好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-17
    • 1970-01-01
    • 2015-07-10
    • 2018-07-07
    • 2021-02-07
    • 2017-11-15
    相关资源
    最近更新 更多