2016-08-18 5 views
1

を渡し、最近私がAngular2とAsp.netコアを学び始め、ここにオブジェクトを投稿するには問題に走った私のコードです:Angularjs2 Postメソッドは空のオブジェクト

Service.tsファイル:

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ファイル:

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コアController

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

これは空のobjecで私のコントローラに当たっています...助けていただければ幸いです。

また、郵便配達員と一緒に試してみるとうまくいきますが、体内の情報に何か問題がありますか?ここで

はそれが仕事をしているとスクリーンショットです:

enter image description here

+0

requestb.inまたはこれらのようなエコーサービスを使用してみてください:http://stackoverflow.com/questions/5725430/http-test-server-that-accepts-get-post-calls – Jim

+0

そしてI https://echo.getpostman.com/ – Jim

答えて

4

あなたは間違った形式でサーバーに投稿しています。

Id=5&Name=Test 

そして、あなたの角度のアプリケーションがこのような何か送っている:だから、どちらかあなたは捨てる

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

あなたの郵便配達の要求は、サーバーがこのようなものである、x-www-form-urlencoded形式を期待していることをほのめかしますJSON.stringifyをクライアント側のメソッドに追加し、フォームデータをクエリ方法で構成し(Content-Typex-www-form-urlencodedに設定する)、またはバックエンドの動作にFromBodyAttributeを追加しますイオン:

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

ありがとうございました:)ちょうど '[FromBody]'属性をコントローラのアクションに追加し、新しいヘッダ({'Content-Type ':' application/json '}) ' – Marius