DntQuitPls DntQuitPls - 3 months ago 21
TypeScript Question

Angularjs2 Post method to asp.net core passes empty object

recently I started learning Angular2 and Asp.net core, ran in to an issue to post an object here is my code:

Service.ts
file:

export class SubCategoryService {
//private headers: Headers;
constructor(private http: Http) {
//this.headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
// this.headers.append('Content-Type', 'application/json');
// this.headers.append('Accept', 'application/json');
}
public createItem = (subCategory: SubCategory): Observable<SubCategory> =>
{
let headers = new Headers();
headers.append('Content-Type', 'application/json');
let toAdd = JSON.stringify(subCategory);
return this.http.post("api/subcategory", toAdd, { headers: headers }).map((response: Response) => <SubCategory>response.json()).catch(this.handleError);

}
}


Component.ts
file:

export class SubCategoryComponent {
constructor(private service: SubCategoryService) { }
subCategories: SubCategory[];
SubCategory: SubCategory = new SubCategory();
onPost() {
this.service.createItem(this.SubCategory).subscribe(
subCategory => this.subCategories.push(subCategory),
error => console.log(error),
() => console.log('Get all items completed'));
this.isLoading = true;

}
}


Asp.Net Core
Controller


[HttpPost]
public async Task<JsonResult> Post(SubCategory subCategory)
{
return new JsonResult("");
}


It hits my controller with empty objec... Please any help would be appreciated.

Also tried with a postman to post it works just fine, maybe is something wrong with the information in a body?

Here is a screenshot with which it does work:

enter image description here

Answer

You are POSTing to the server in a wrong format.

Your postman request hints that your server is expecting x-www-form-urlencoded format, which is something like this:

Id=5&Name=Test

And your Angular application is sending something like this:

{"Id":5,"Name":"Test"}

So either you ditch JSON.stringify in your client-side method and construct the form data the query way (as well as set the Content-Type to x-www-form-urlencoded), or add FromBodyAttribute to your back-end action:

public async Task<JsonResult> Post([FromBody]SubCategory subCategory)