最近我开始学习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 Core Controller
[HttpPost]
public async Task<JsonResult> Post(SubCategory subCategory)
{
return new JsonResult("");
}
它以空对象命中我的控制器...请不要帮助。
还尝试用邮递员发布它工作得很好,也许是身体中的信息有问题?
以下是它可以正常运行的屏幕截图:
答案 0 :(得分:5)
您正以错误的格式向服务器发帖。
您的邮递员请求暗示您的服务器期望x-www-form-urlencoded
格式,如下所示:
Id=5&Name=Test
你的Angular应用程序发送的内容如下:
{"Id":5,"Name":"Test"}
因此,您要么在客户端方法中抛弃JSON.stringify
并使用查询方式构建表单数据(以及将Content-Type
设置为x-www-form-urlencoded
),或者添加{{1你的后端行动:
FromBodyAttribute