简体   繁体   中英

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. When I send POST data from the client, it is reaching as null value in the server. 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:

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.
  • 2 -From your code, you are receiving it as string and your client are passing it as json format.
  • 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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