2016-08-18 17 views
1

最近我开始学习Angular2和Asp.net核心,跑了一个问题,在这里发布的对象是我的代码:Angularjs2 POST方法asp.net核心传递空对象

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(""); 
    } 

它击中我的控制器与空对象...请任何帮助,将不胜感激。

也尝试与邮递员发布它工作得很好,也许是错误的信息在身体?

这是与它的工作截图:

enter image description here

+0

尝试使用回声服务像requestb.in或这些:http://stackoverflow.com/questions/5725430/http-test-server-that-accepts-get-post-calls – Jim

+0

我只是今天看到这一个,我想尝试:https://echo.getpostman.com/ – Jim

回答

4

你正在一个错误的格式发送到服务器。

你的邮递员要求暗示你的服务器要求x-www-form-urlencoded格式,它是这样的:

Id=5&Name=Test 

而且你的角度应用程序发送这样的事情:

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

因此,无论你沟JSON.stringify,并以查询的方式构建表单数据(以及将Content-Type设置为x-www-form-urlencoded),或将FromBodyAttribute添加到您的后端操作离子:

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

谢谢它的工作:)只是添加了一个'[FromBody]'属性控制器的行动,并留下'新的头({'内容类型':'application/json'})' – Marius

相关问题