ASP.NET Core 3.0-CreatedAtRoute-没有路由与提供的值匹配

时间:2019-10-01 11:34:12

标签: asp.net-core-3.0

从2.2更新到ASP.NET Core 3.0之后,No route matches the supplied values在执行CreateAsync之后出现。这是由CreatedAtAction引起的。我试图将GetByIdAsync的属性设置为[HttpGet("{id}", Name = "Get")],但没有成功。我检查了其他相关线程,但是我的代码对我来说很好。

// GET: api/Bots/5
[HttpGet("{id}")]
public async Task<ActionResult<BotCreateUpdateDto>> GetByIdAsync([FromRoute] int id)
{
    var bot = await _botService.GetByIdAsync(id);

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

    return Ok(_mapper.Map<BotCreateUpdateDto>(bot));
}

// POST: api/Bots
[HttpPost]
public async Task<ActionResult<BotCreateUpdateDto>> CreateAsync([FromBody] BotCreateUpdateDto botDto)
{
    var cryptoPair = await _botService.GetCryptoPairBySymbolAsync(botDto.Symbol);

    if (cryptoPair == null)
    {
        return BadRequest(new { Error = "Invalid crypto pair." });
    }

    var timeInterval = await _botService.GetTimeIntervalByIntervalAsync(botDto.Interval);

    if (timeInterval == null)
    {
        return BadRequest(new { Error = "Invalid time interval." });
    }

    var bot = new Bot
    {
        Name = botDto.Name,
        Status = botDto.Status,
        CryptoPairId = cryptoPair.Id,
        TimeIntervalId = timeInterval.Id
    };

    try
    {
        await _botService.CreateAsync(bot);
    }
    catch (Exception ex)
    {
        return BadRequest(new { Error = ex.InnerException.Message });
    }

    return CreatedAtAction(nameof(GetByIdAsync), new { id = bot.Id }, _mapper.Map<BotCreateUpdateDto>(bot));
}

2 个答案:

答案 0 :(得分:12)

我有同样的问题。我只将endpoints.MapControllers();更改为endpoints.MapDefaultControllerRoute();。第一个没有指定任何路由,第二个设置了默认路由。

app.UseEndpoints(endpoints =>
{
    endpoints.MapDefaultControllerRoute();
});

答案 1 :(得分:0)

除了上面的 .MapDefaultControllerRoute() 之外,我还必须根据(并从)下面评论中提到的 URL 构造两个端点,如下所示。


 [HttpPost]
[Route( "CreateServedByMedicalItem" )]
public IActionResult HTTPpost( [FromBody] ServedByMedicalDTO aServedByMedicalCreateDto )
        {
            string userName = "userToDo"; 
            ServedByMedical aServedByMedicalItem;
            try
            {
                if (aServedByMedicalCreateDto == null)
                {
                    throw new Exception( "Input aServedByMedicalCreateDto did not translate into a ServedByMedicalDTO." );
                }
                aServedByMedicalItem = EMX2.ToInsertServedByMedical( aServedByMedicalCreateDto, userName, _mapper );

                int MedicalItemId = _repo.EFadd( aServedByMedicalItem ); 
// this is only puts commands in the queue, but with new/next id ???

                if (MedicalItemId == 0
                        && aServedByMedicalItem.ExceptionInfo != null
                        && aServedByMedicalItem.ExceptionInfo.Length > 0)
                {
                    throw new Exception( aServedByMedicalItem.ExceptionInfo );
                }

             var Id = aServedByMedicalItem.IdForComplaint;
             return CreatedAtRoute(
                routeName: "MethGetOneServedByMedical",
                routeValues:new
                            {
                                UniqueIdOfOneComplaint = Id 
                            },
                value: aServedByMedicalItem
                ); // HTTP 201
            }
            catch (Exception ex)
            {
                string msg = ex.Message;
                if (ex.InnerException != null)
                {
                    msg = msg + " | " + ex.InnerException.Message.ToString();
                }
                return BadRequest( msg );
            }

// REST standard is to have the URI of the new row passed back in HEADER 
// (location)
        }



[HttpGet( "GetOneServedByMedical/{UniqueIdOfOneComplaint:int}", Name = nameof( MethGetOneServedByMedical ))] // https://github.com/microsoft/aspnet-api-versioning/issues/558
[ActionName( "GetOneServedByMedical" )] 
// https://www.josephguadagno.net/2020/07/01/no-route-matches-the-supplied-values
// however, I had to hard code "GetOneServedByMedical" to be the endpoint name 
// recognized by CreatedAtRoute in HTTPpost
        public IActionResult MethGetOneServedByMedical( int UniqueIdOfOneComplaint )
        {
            // Instantiate source object
            // (Get it from the database or whatever your code calls for)

    var obj = _repo.GetServedByMedicalGivenComplaintId( UniqueIdOfOneComplaint );

    ServedByMedicalViewModel _view = _mapper.Map<ServedByMedicalViewModel>( obj );
                return Ok(_view);
            }