rah*_*wla 2 api entity-framework put http-method angular
我有使用实体框架的 c# WEB API - 我试图通过我的角度前端发出放置请求以模拟“签入”功能,但请求未通过。
这是我的 Web api 方法
[HttpPut("checkin/{id}")]
[AuthorizeRoles(Role.Administrator, Role.User)]
public async Task<IActionResult> CheckIn(int id)
{
var reservation = await context.Reservations.FindAsync(id);
var username = User.Identity.Name;
if (reservation == null)
return NotFound();
// Ensure user is checking-in their own reservation and its not already checked-in
if (reservation.UserName == username && reservation.CheckInDate == null)
{
reservation.CheckInDate = DateTime.Now;
var count = await context.SaveChangesAsync();
if (count < 1)
return StatusCode((int)HttpStatusCode.InternalServerError);
}
return Ok();
}
Run Code Online (Sandbox Code Playgroud)
这是我的两个 .ts 文件,其中正在发起请求 - 注意:在第二种方法中,我决定手动传递 ID 以用于测试目的
-checkIn(id: number){
if (confirm('Would you like to check in')) {
this.reservationService.checki(7);
};
}
Run Code Online (Sandbox Code Playgroud)
预订服务.ts
checki(id: number) {
const headers = new Headers();
const url = `${this.url}+/checkin/${7}`;
return this.http
.put(url, JSON.stringify(7), {headers: headers})
.map(res => res.json());
}
Run Code Online (Sandbox Code Playgroud)
使用 Angular HTTP 客户端,所有 Http 请求都是 Observables,这意味着您需要订阅它们才能调用它们。
因此,在您的签入功能中,您需要执行以下操作:
-checkIn(id: number){
if (confirm('Would you like to check in')) {
this.reservationService.checki(7).subscribe(res => {});
};
}
Run Code Online (Sandbox Code Playgroud)
无需显式处理响应。
至于处理 put 的后端,我会看看这个答案,无论如何我都不是 c# 专家。/sf/answers/2298473061/