Angular5 post seems to be posting null values to webapi core controller


Getting Angular5/6 HttpClient to post JSON object to a WebAPI (.Net Core) seems to be passing null value to your simple/complex model for example, EmployeeModel.

 There are alot of component you need to get right. Key changes include:-


a) CORS Setup - In your WebApi's Startup.cs you need to configure CORS correctly.  Please have a look at code below, i have configure my CORS to accept any methods and any header.


app.UseCors(option => option.WithOrigins("*").AllowAnyMethod().AllowAnyHeader());

The complete code snippet is shown here.


b) Header - You need to configure 'Content-Type' wth application/json in your HTTP POST calls and not forgetting the subscribe() method call - to execute method now. :)




const headers = new HttpHeaders().set('Content-Type', 'application/json; charset=utf-8');
this.http.post(APPLICATION_HOST + '/user/save',
"{name:'jeremy', username : 'wooo'}", {headers : headers}).subscribe(data =>
{ console.log(data);
});



c) Controller  method needs a FromBody attribute. As we all know, webap controller uses JsonFormatter as the default formatter to work with content post to it.

The FromBody tells webapi to get the content from message body and pass this on to content negotiator.

If you miss any of these steps here, it probably not going to work.

Hope this helps.


Comments

Popular posts from this blog

ionic2 cordova build android - Unable resolve gradle 2.2.3

A quick tutorial for OWASP ZAP tool for beginners