简体   繁体   English

c#webApi从Angular 2客户端发布时到达空数据

[英]c# webApi reaching null data when posting from Angular 2 client

I've set up a Angular 2 client and a C#.NET Core WebApi to comunicate between them. 我已经设置了Angular 2客户端和C#.NET Core WebApi,以便在它们之间进行通信。 When I send POST data from the client, it is reaching as null value in the server. 当我从客户端发送POST数据时,它在服务器中达到空值。 The controller being called is; 被调用的控制器是;

[HttpPost]
    public ActionResult Post([FromBody] string descr) // descr aways null
    {
        if (!string.IsNullOrEmpty(descr))
        {
            try
            {
                Restaurante novo = new Restaurante(descr);
                cnx.Restaurantes.Add(novo);
                cnx.SaveChanges();
                return Ok(novo);
            }
            catch
            {
                return NotFound();
            }
        } else return BadRequest();

    }

The part of the client that generates the JSon data: 客户端生成JSon数据的部分:

postRestauranteHttp(nome: string) : Observable<IRestaurante>{

    console.log("nome: " + nome);
    let body = JSON.stringify({ 'descr' : nome });
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });

    return this._http.post("http://address/to/api" , body, options)
    .map((response: Response) => <IRestaurante>response.json())
    .catch(this.handleError);
}

What could be causing this? 是什么原因造成的?

  • 1 -First check if the json are properly formatted before send it to controller, otherwise its not possible for api controller recognize it. 1-首先检查json是否正确格式化,然后再将其发送到控制器,否则api控制器无法识别它。
  • 2 -From your code, you are receiving it as string and your client are passing it as json format. 2-从您的代码中,您以字符串形式接收它,而客户端以json格式传递它。
  • 3 -You need to concatenate with ' ' before and after the body, to send it as string or change the controller to receive as you want. 3-您需要在正文前后用''串联起来,以字符串形式发送它或更改控制器以根据需要接收。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM