我正在構建一個帶有angular2前端和.NET後端的站點,對後端的GET調用一直在完美地工作。從angular2到.NET web api的HTTP發佈不起作用
現在我想發佈一些東西到我的服務器,但我似乎無法得到它的工作。
角2服務方法
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[]
){}
}
.NET DTO模型
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 WEB API控制器
[HttpPost]
[Route("add")]
public IHttpActionResult PostCategory([FromBody]CategoryDTO category)
{
var newCategory = _categoryService.AddCategory(_dtoBuilder.CategoryDtoToCategory(category));
if(newCategory == null) return NotFound();
return Ok(_dtoBuilder.CategoryToDto(newCategory));
}
端點對應,模型對應。
調用正在進行中,我在控制器的開始處放置了一個斷點,以查看它是否進入,但是我沒有。我錯過了什麼嗎?
謝謝!
編輯:
方法獲取的卡列斯在這裏:
@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>
你在哪裏訂閱'postCategory'? – echonax
postCategory get從我的一個組件中調用。已經測試過正在進行POST調用。 – TanguyB
請在你的問題中分享你的代碼。你是如何測試它的?你能否也包括迴應? – echonax