gpt4 book ai didi

c# - 如何使用方法 CreatedAtRoute() 响应发布请求

转载 作者:行者123 更新时间:2023-12-05 05:01:35 25 4
gpt4 key购买 nike

我在使用以下代码时遇到问题,现在我明白问题出在哪里了,但我没有解决方案来让代码执行我想要的操作。

// POST: api/Airports
[HttpPost]
public async Task<ActionResult<Airport>> CreateAirport(AirportCreateDto airportCreateDto)
{
var airportModel = _mapper.Map<Airport>(airportCreateDto);
_repository.CreateAirport(airportModel);
await _repository.SaveChanges();

var airportReadDto = _mapper.Map<AirportReadDto>(airportModel);

return CreatedAtRoute(nameof(GetAirport), new { airportReadDto.ID }, airportReadDto);
}

CreatedAtRoute() 方法是问题所在。现在,GetAirport 是 Task 类型,这可能是问题的原因。

这里是错误

System.InvalidOperationException: No route matches the supplied values.
at Microsoft.AspNetCore.Mvc.CreatedAtRouteResult.OnFormatting(ActionContext context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ObjectResultExecutor.ExecuteAsyncCore(ActionContext
context, ObjectResult result, Type objectType, Object value)
at Microsoft.AspNetCore.Mvc.Infrastructure.ObjectResultExecutor.ExecuteAsync(ActionContext context,
ObjectResult result)
at Microsoft.AspNetCore.Mvc.ObjectResult.ExecuteResultAsync(ActionContext context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultAsync(IActionResult result)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext[TFilter,TFilterAsync](State&
next, Scope& scope, Object& state, Boolean& isCompleted)
at
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeNextResultFilterAsync[TFilter,
TFilterAsync
]()

是否有一种解决方案可以让我继续使用类型为 Task 的 CreatedAtRoute() 和 GetAirport?

这是获取机场的代码

// GET: api/Airports/5
[HttpGet("{id}")]
public async Task<ActionResult<Airport>> GetAirport(int id)
{
var airport = await _repository.GetAirportById(id);

if (airport == null)
{
return NotFound();
}

return Ok(_mapper.Map<AirportReadDto>(airport.Value));
}

最佳答案

System.InvalidOperationException: No route matches the supplied values.

您可以尝试如下显式设置路由名称,这对我有用。

[HttpGet("{id}", Name = "GetAirport")]
public async Task<ActionResult> GetAirport()
{
//...

Action 方法CreateAirport

[HttpPost]
public async Task<ActionResult<Airport>> CreateAirport(AirportCreateDto airportCreateDto)
{
//...

return CreatedAtRoute(nameof(GetAirport), new { id = airportReadDto.ID }, airportReadDto);
}

测试结果

enter image description here

关于c# - 如何使用方法 CreatedAtRoute() 响应发布请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62668114/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com