web-dev-qa-db-ja.com

ASP.NETコア3 Web APIで複数のエンドポイントを処理する方法

intタイプ入力とstringタイプ入力の場合は、最初にHTTP GETリクエストを処理するための2つの方法があります。

_//GET : api/Fighters/5
[HttpGet("{id}")]
public async Task<ActionResult<Fighter>> GetFighter(int id) 
{
    var fighter = await _context.Fighters.FindAsync(id);

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

// GET: api/Fighters/Alex
[Route("api/Fighters/{name}")]
[HttpGet("{name}")]
public async Task<ActionResult<IEnumerable<Fighter>>> GetFighter (string name) 
{
    return await _context.Fighters.Where(f => f.Name == name).ToListAsync();
}
_

hTTPを送信するとこの例外が表示されます(Postman)。

_Microsoft.AspNetCore.Routing.Matching.AmbiguousMatchException: The request matched multiple endpoints. Matches: 

FighterGameService.Controllers.FightersController.GetFighter (FighterGameService)
FighterGameService.Controllers.FightersController.GetFighter (FighterGameService)
FighterGameService.Controllers.FightersController.GetFighter (FighterGameService)
FighterGameService.Controllers.FightersController.GetFighter (FighterGameService)
   at Microsoft.AspNetCore.Routing.Matching.DefaultEndpointSelector.ReportAmbiguity(CandidateState[] candidateState)
   at Microsoft.AspNetCore.Routing.Matching.DefaultEndpointSelector.ProcessFinalCandidates(HttpContext httpContext, CandidateState[] candidateState)
   at Microsoft.AspNetCore.Routing.Matching.DefaultEndpointSelector.Select(HttpContext httpContext, CandidateState[] candidateState)
   at Microsoft.AspNetCore.Routing.Matching.DfaMatcher.MatchAsync(HttpContext httpContext)
   at Microsoft.AspNetCore.Routing.Matching.DataSourceDependentMatcher.MatchAsync(HttpContext httpContext)
   at Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.Invoke(HttpContext httpContext)
   at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.HttpsPolicy.HttpsRedirectionMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
_

_GET api/fighters/11_ "がintまたはstringのいずれかである可能性があるため、明らかにエラーが発生しますので、2つのメソッドを組み合わせることで問題を解決しました。

_// GET: api/Fighters/5
// GET: api/Fighters/Alex
[HttpGet("{idOrName}")]
public async Task<ActionResult<IEnumerable<Fighter>>> GetFighter(string idOrName)
{
    if (Int32.TryParse(idOrName, out int id))
    {
        return await _context.Fighters.Where(f => f.Id == id).ToListAsync();
    }
    else
    {
        return await _context.Fighters.Where(f => f.Name == idOrName).ToListAsync();
    }

}
_

しかし、これはまったく気分が良くない。この問題を処理するための適切な方法は何ですか?

4
merkithuseyin

.NET CORE 3.1以上のソリューションに従って、[route( "routename")]を使用してください。

[HttpPost]
        [Route("CreateUserRole")]
       // [Authorize(Roles = "admin")]
        [ProducesResponseType(StatusCodes.Status201Created)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status500InternalServerError)]
        public async Task<IActionResult> CreateUserRole([FromBody] AssignUserRole assignUserRole)
        {
            try
            {
                _logger.LogInfo("Attempted submission attempted");

                if (assignUserRole == null)
                {
                    _logger.LogWarn("Empty request submitted");
                    return BadRequest(ModelState);
                }
                if (!ModelState.IsValid)
                {
                    _logger.LogWarn("User data was incomplete");
                    return BadRequest(ModelState);
                }
                var User = _Mapper.Map<Users>(assignUserRole);
                _UserRoleRepository.AssignRoleUser(assignUserRole);
                _logger.LogInfo("User Role created");
                Audit_logs audit = new Audit_logs()
                {
                    uid = User.id,
                    action = "Create User Role",
                    log = $"{assignUserRole.rolename} Role has created",
                    datetime = DateTime.Now
                };
                await _audit_Logs.Create(audit);
                return Created("Create User Role", new { assignUserRole });
            }
            catch (Exception ex)
            {
                return InternalError($"{ex.Message}-{ex.InnerException}");
            }

        }
 _
0
Papun Sahoo