我的服务器/客户端应用程序具有以下控制器。但是,当我发布/创建保留时,发布操作超出范围时,它不会保留/缓存(id)属性的值返回(CreatedAtAction(nameof(GetById)
,new{id=order.id}, order}
方法。因此,GetById(int id)
不会接收到生成的最后一个ID,而是显示为0。但是,数据会以有效ID成功提交到数据库中。
服务器端控制器:
[HttpGet("{id:int}")]
public ActionResult<OrderTable> GetById(int id)
{
var order = _context.ReservationsTables.FirstOrDefault(o => o.Id == id);
if(order == null)
{
return NotFound();
}
else
{
return order;
}
}
[HttpPost]
public ActionResult<OrderTable> CreateOrder(OrderTable order)
{
_context.ReservationsTables.Add(order);
_context.SaveChanges();
return CreatedAtAction(nameof(GetById), new { id = order.Id }, order);
}
客户端控制器:
public async Task<IActionResult> CreatePostAsync(OrderTable order)
{
var httpClient = _clientFactory.CreateClient();
HttpResponseMessage response = await httpClient.PostAsJsonAsync("https://localhost:44387/api/Reservation", order);
if (response.IsSuccessStatusCode)
{
var orderResult = await response.Content.ReadAsAsync<OrderTable>();
return RedirectToAction("ThankYouAsync", new { id = order.Id });
}
else
{
return View("An error has occurred");
}
}
public async Task<IActionResult> ThankYouAsync(int orderId)
{
var httpClient = _clientFactory.CreateClient();
httpClient.BaseAddress = new Uri("https://localhost:44387/");
HttpResponseMessage response = await httpClient.GetAsync("api/Reservation/" + orderId);
if (response.IsSuccessStatusCode)
{
var orderResult = await response.Content.ReadAsAsync<OrderTable>();
return View(orderResult);
}
else
{
return View("An error has occurred");
}
}
[HttpGet]
public async Task<IActionResult> Create()
{
await PopulateRestaurantDropDownListAsync();
return View();
}
答案 0 :(得分:2)
重定向的操作具有以下签名
Task<IActionResult> ThankYouAsync(int orderId)
请注意,参数名称为orderId
。
完成重定向后,
return RedirectToAction("ThankYouAsync", new { id = order.Id });
已定义值对象new { id = order.Id }
参数名称必须匹配才能正常工作。
因此更新RedirectToAction
以使用正确的属性名称
return RedirectToAction("ThankYouAsync", new { orderId = order.Id });
请注意值对象中的new { orderId = order.Id }
具有匹配的orderId
参数。