Reputation: 1583
I am developing an app in Angular 5.
http.get
service is working fine here but getting problem in http.post
.
Below is my code:
GetEmployee() {
//Data needs to be grouped in an object array as payload
var payload = { "StaffCode": this.employeeCode };
this.showLoader = true;
this.http.post<StaffInfo>(this.baseURL + 'api/StaffDetail/GetEmployee', JSON.stringify(payload)).subscribe(result => {
this.Staff = result;
this.showLoader = false;
}, error => console.error(error));
}
And API in .net core:
[HttpPost("[action]")]
public Employee GetEmployee(string StaffCode)
{
return util.GetEmployee(StaffCode);
}
I am calling it on button click
<button type="button" (click)="GetEmployee()" class="btn btn-sm btn-warning">Get Detail</button>
but in my API it is null.
Am I calling post API in the wrong way?
One more thing, if I add [FromBody]
before parameter signature than it does not even hit the API.
Upvotes: 1
Views: 419
Reputation: 247521
Client is sending a complex object model but action expects simple string.
Create model to match payload from client.
public class GetEmployeeModel {
public string StaffCode { get; set; }
}
update action to expect payload in the body of the post.
[HttpPost("[action]")]
public Employee GetEmployee([Frombody]GetEmployeeModel model) {
return util.GetEmployee(model.StaffCode);
}
Also ensure that the payload is constructed correctly on the client and sent with the correct content type
var payload = { StaffCode: this.employeeCode };
var json = JSON.stringify(payload);
var url = this.baseURL + 'api/StaffDetail/GetEmployee';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
this.http.post<StaffInfo>(url, json, httpOptions).subscribe(result => {
this.Staff = result;
this.showLoader = false;
}, error => console.error(error));
Now ideally, given the name of the action and the expected functionality, you would be better off refactoring the action to a HTTP GET request passing the code in the route
[HttpGet("[action]/{StaffCode}")]
public Employee GetEmployee(string StaffCode)
{
return util.GetEmployee(StaffCode);
}
And updating the client accordingly to make the request to
var url = this.baseURL + 'api/StaffDetail/GetEmployee/' + this.employeeCode;
this.http.get<StaffInfo>(url).subscribe(result => {
this.Staff = result;
this.showLoader = false;
}, error => console.error(error));
Upvotes: 4