Asp.net 从angular2到.NET web api的HTTP Post不';行不通
我正在构建一个带有angular2前端和.NET后端的站点,对后端的GET调用工作得非常完美 现在我想发布一些东西到我的服务器上,但我似乎无法让它工作 角度2服务方法Asp.net 从angular2到.NET web api的HTTP Post不';行不通,asp.net,http,angular,post,asp.net-web-api,Asp.net,Http,Angular,Post,Asp.net Web Api,我正在构建一个带有angular2前端和.NET后端的站点,对后端的GET调用工作得非常完美 现在我想发布一些东西到我的服务器上,但我似乎无法让它工作 角度2服务方法 postCategory(category: Category){ let endpoint = this.url + 'add'; let body = JSON.stringify(category); let options = new RequestOptions({headers: this.he
postCategory(category: Category){
let endpoint = this.url + 'add';
let body = JSON.stringify(category);
let options = new RequestOptions({headers: this.headers});
return this.http.post(endpoint, body, options)
.map((res:Response) => res.json())
.catch((error:any) => Observable.throw(error.json().error || 'Server Error'));
}
角度2 DTO模型
export class Category{
constructor(
public CategoryName: string,
public ParentId: number,
public ChildCategories: Category[]
){}
}
public class CategoryDTO
{
public string CategoryName { get; set; }
public int? ParentId { get; set; }
public IList<CategoryDTO> ChildCategories { get; set; }
public CategoryDTO(string name, int? parent, IList<CategoryDTO> child)
{
CategoryName = name;
ParentId = parent;
ChildCategories = child;
}
}
.NET DTO模型
export class Category{
constructor(
public CategoryName: string,
public ParentId: number,
public ChildCategories: Category[]
){}
}
public class CategoryDTO
{
public string CategoryName { get; set; }
public int? ParentId { get; set; }
public IList<CategoryDTO> ChildCategories { get; set; }
public CategoryDTO(string name, int? parent, IList<CategoryDTO> child)
{
CategoryName = name;
ParentId = parent;
ChildCategories = child;
}
}
端点对应,模型对应
正在打电话,我在控制器的开始处放了一个断点,看它是否进入,但我没有。我错过什么了吗
谢谢
编辑:
方法Get在此处调用:
@Component({
moduleId: module.id,
selector: 'admin-category',
templateUrl: 'admin-category.component.html',
styleUrls: ['admin-category.component.css']
})
export class AdminCategoryComponent{
name: string;
parent: number;
constructor(
private categoryService: CategoryService
){}
addCategory(): void{
this.categoryService.postCategory(new Category(this.name, this.parent, null));
}
}
该组件的模板:
<h1>Add Category</h1>
<div class="form-group">
<label for="name">Name:</label>
<input type="text" class="form-control" id="name" [(ngModel)]="name">
</div>
<div class="form-group">
<label for="parent">ParentId:</label>
<input type="text" class="form-control" id="parent" [(ngModel)]="parent">
</div>
<button class="btn btn-default" (click)="addCategory()">Submit</button>
添加类别
姓名:
父ID:
提交
除非您订阅,否则Observable不会发出请求,因此您不会进行后端呼叫
你应该像这样订阅它:
this.categoryService.postCategory(new Category(this.name, this.parent, null)).subscribe((response)=>{
console.log(response);
});
您在哪里订阅postCategory
?postCategory从我的一个组件调用。已测试正在进行POST呼叫。请在您的问题中分享您订阅的代码。你是怎么测试的?你还可以包括回答吗?你没有回答我的问题:)而且你的问题没有告诉我“实际的POST呼叫没有问题。后端只是“忽略”它。”@TanguyB你能分享你调用此方法的代码吗?我现在就测试它。谢谢你是老板@TanguyB哈哈,很高兴我能帮上忙。