简体   繁体   中英

asp.net core post api always receive null

Here is my angular 6 code

saveQuestion(value : string) : Observable<string> {
    console.log(value)
    let params = new HttpParams();
    params = params.set('id', value);
    return this._http.post<string>(this.subjectAPi + 'api/Question/Save/', {params});
}

below is my .net core code

[HttpPost("[action]")]
public IActionResult Save([FromBody]string id)
{
    Question ob = new Question();
    ob.update(id)  // id is always null
    return Ok("1");
}

ID is always null. Suggestion will be really appreciated

If I'm not mistaking, ASP.NET Core does not work with camelCasing for JSON by default. Try renaming the id in the HttpParams to be Id .

saveQuestion(value : string) : Observable<string> {
    let params = new HttpParams();
    params = params.set('Id', value);
    return this._http.post<string>(this.subjectAPi + 'api/Question/Save/', {params});
}

The HttpParams is for preparing URL encoded parameters, if you'd like to post a body in JSON you don't need that. Try just simply create your data like:

let body = { id: value }
this._http.post<string>(this.subjectAPi + 'api/Question/Save/', body);

If you really want to post your body as URL encoded data try to set the Content-Type request header:

this._http.post<string>(this.subjectAPi + 'api/Question/Save/', params.toString(), {
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
});

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