【问题标题】:Angular4 http post method pass empty values to web apiAngular4 http post方法将空值传递给web api
【发布时间】:2018-08-22 17:09:29
【问题描述】:

我将 http post 方法从 angular4 组件调用到 web api。当我在控制台上打印从 web api 返回的这些值时,它会打印空值。我也使用邮递员检查了请求。它也没有工作。

来自组件文件的 Http post 调用。

EditValue(event, name, id) {
  const headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
  const options = new RequestOptions({ headers: headers });
  let body = { "name" : name, "id": id }
  this.http_.post('http://localhost:12412/api/employee?', body, options)
    .subscribe((data) => {console.log(data)});
}

web api 中的 Http post 方法。

[HttpPost]            
public string postemp(Model model)
{
    return "name:" +model.name + " , " + "id: " + model.id;
}

public class Model
{
    public int id { get; set; }
    public string name { get; set; }
}

当我从 Editvalue 函数中检查名称和 ID 时,这些值正在传递。我也尝试了Angular4 http post method does not pass data to web api 给出的解决方案。但问题没有解决。如何检查那些发布的数据是否传递给 web api post 方法?

我附上了下面得到的响应结果。

【问题讨论】:

  • 你能改变内容类型吗? ..,你试过了吗?
  • 你在用HttpClient吗?
  • 没有。我用的是Http。
  • 您是否检查了 EditValue 函数上的传入参数值?您可以尝试将它们登录到您的控制台吗?
  • @E.L.N.D.Madubhashini 您的问题与Angular4 http post method does not pass data to web api 中的问题不同吗?

标签: html angular typescript asp.net-web-api


【解决方案1】:

在向 webapi 发送一次之前尝试JSON.stringify(body)

【讨论】:

  • 仍然得到相同的结果。
【解决方案2】:

您正在以 JSON 格式发送正文中的信息。但是在您的标头中,您设置了application/x-www-form-urlencoded,其中的值被编码在由“&”分隔的键值元组中,键和值之间有一个“=”。因此,为了能够以 JSON 格式发送数据,您需要将标头中的 Content-Type 更改为 application/json

【讨论】:

  • 在我将内容类型更改为 application/json 后,它会出现类似“无法加载 localhost:12412/api/employee?:预检响应的 HTTP 状态代码无效 405”之类的错误。
  • 您需要在 body 元素上使用 JSON.stringify() 以获取 JSON 表示以在 http post 方法中使用。
【解决方案3】:

只需将[FromBody] 属性用于您的 API 方法参数,如下所示。

[HttpPost]            
public string postemp([FromBody]Model model)
{
    return "name:" +model.name + " , " + "id: " + model.id;
}

【讨论】:

    【解决方案4】:

    由于我在这里使用的内容类型是 'application/x-www-form-urlencoded',因此不应使用 JSON 对象传递正文。我在这里传递的正文应该在如下查询字符串中。

    let body="id="+id+"&name="+name;

    它对我有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-04
      • 1970-01-01
      相关资源
      最近更新 更多