2

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

  • Try using an echo service like requestb.in or these: http://stackoverflow.com/questions/5725430/http-test-server-that-accepts-get-post-calls – Jim Aug 18 '16 at 20:26
  • And I just saw this one today that I want to try: https://echo.getpostman.com/ – Jim Aug 18 '16 at 20:27

1 Answers1

5

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)
Harry Ninh
  • 16,288
  • 5
  • 60
  • 54
  • Thanks it worked :) Just added a `[FromBody]` attribute to controller action and left `new Headers({ 'Content-Type': 'application/json' })` –  Aug 19 '16 at 06:07