【问题标题】:POST request : Webapi receives empty content from angular clientPOST 请求:Webapi 从 Angular 客户端接收空内容
【发布时间】:2018-04-19 06:59:43
【问题描述】:

我正在尝试将一个对象发布到我的 API,但它无法在那里使用。

客户代码

const url = '/odata/StammVersicherter';
        const headers = new Headers();
        headers.append('Content-Type', 'application/json');
        const requestBody = JSON.stringify(data);
        return this._http.post(url, requestBody , { headers: headers }).map(
            res => {
                // do something with the response
            }
        );

产生的请求

API 代码

public async Task<IHttpActionResult> Post([FromBody]Data data)
    {
      string content = await this.Request.Content.ReadAsStringAsync(); // empty! 
      if (!ModelState.IsValid)
      {
        return BadRequest(ModelState);
      }
      _dataContext.Data.Add(data);

      await _dataContext.SaveChangesAsync();

      return Created(versicherter);
    }

当此调用到达我的 api 方法时,Data 对象为空。有什么快速的想法吗?

【问题讨论】:

  • 我显然没有给予应有的关注。反序列化已开始,但完成时出现错误。 (无法转换为数字的字符串)。

标签: post asp.net-web-api http-post


【解决方案1】:

当您使用 POST 请求时,您应该使用 "content-type": "application/x-www-form-urlencoded",

以下是javascript中的参考代码。

var settings = {
  "async": true,
  "crossDomain": true,
  "url": "your URL HERE",
  "method": "POST",
  "processData": false,
  "contentType": false,
  "content-type": "application/x-www-form-urlencoded",
   "data": {
"username": "srussell@org.com.au.test",
"password": "test",
 }    }

$.ajax(settings).done(function (response) {
  console.log(response);
});

【讨论】:

  • 因为我发送的是纯 json 而不是 formdata 对象,所以这也不起作用。应该可以发送 JSON 而不用 formData 包装。
【解决方案2】:

在这种情况下,您可以发送如下所示的数据,但您的 json 数据键字段应与服务器端的模型匹配。

var settings = {
      "async": true,
      "crossDomain": true,
      "url": "Your URL",
      "method": "POST",
      "headers": {
        "content-type": "application/json",
        "cache-control": "no-cache",

      },
      "processData": false,
      "data": "{\"Name\":\"abc\",\"EMail\":\"abc@xyz.com\"}"
    }

    $.ajax(settings).done(function (response) {
      console.log(response);
    });

【讨论】:

    【解决方案3】:

    正如我对原始问题的评论所示:JSON 序列化程序遇到错误,导致内容为空

    【讨论】:

      猜你喜欢
      • 2023-03-27
      • 2021-09-13
      • 1970-01-01
      • 2017-07-31
      • 1970-01-01
      • 2017-03-29
      • 2016-03-01
      • 2021-08-04
      • 1970-01-01
      相关资源
      最近更新 更多