代码之家  ›  专栏  ›  技术社区  ›  Sebastian Edelmeier

POST请求:Webapi从angular客户端接收空内容

  •  2
  • Sebastian Edelmeier  · 技术社区  · 6 年前

    我试图将一个对象发布到我的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
                }
            );
    

    产生的请求 enter image description here

    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方法时,数据对象为null。有什么快速的想法吗?

    3 回复  |  直到 6 年前
        1
  •  1
  •   Saveen    6 年前

    由于您正在使用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);
    });
    
        2
  •  1
  •   Saveen    6 年前

    在这种情况下,您可以像下面这样发送数据,但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
  •  0
  •   Sebastian Edelmeier    6 年前

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