ASP.NET Core 3.0: CreatedAtRoute: ни один маршрут не соответствует предоставленным значениям

После обновления до ASP.NET Core 3.0 с версии 2.2 я получаю сообщение об ошибке:

Ни один маршрут не соответствует предоставленным значениям

Это появляется сразу после выполнения 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));
}

person nop    schedule 01.10.2019    source источник


Ответы (2)


У меня была такая же проблема. Я только изменил endpoints.MapControllers(); на endpoints.MapDefaultControllerRoute();. Первый не указывает никаких маршрутов, а второй устанавливает маршрут по умолчанию.

app.UseEndpoints(endpoints =>
{
    endpoints.MapDefaultControllerRoute();
});
person Electron    schedule 01.10.2019
comment
Есть ли какие-нибудь дискуссии о том, почему они это изменили? - person Baklap4; 04.10.2019

Помимо .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);
            }



person sef    schedule 05.01.2021