最近我开始学习angular2和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("");
}
它用空的目标击中我的控制器…请提供任何帮助。
也试过和邮递员一起寄出它的效果很好,也许是身体里的信息有问题吗?
这是一张截图,它确实可以使用:
最佳答案
您以错误的格式发布到服务器。
您的邮递员请求提示您的服务器需要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)