首页 > 解决方案 > 通过 Angular 传递的 Web Api 参数为空

问题描述

因此,我试图通过 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');
    });
  }

标签: .netangular

解决方案


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

在文档上备注:

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

来源:发送简单类型

另外,这个博客比我解释得更好。


推荐阅读