简体   繁体   English

如何正确处理 ASP.Net Core 3 Web API 中的多个端点

[英]How to handle multiple endpoints in ASP.Net Core 3 Web API properly

I have 2 methods to handle HTTP GET requests, first one for int type input and the other one for string type input.我有两种方法来处理 HTTP GET 请求,第一种用于int类型输入,另一种用于string类型输入。

//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();
}

when i send HTTP GET this exception appears (in Postman):当我发送 HTTP GET 时出现此异常(在邮递员中):

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/1 would cause error obviously since " 1 " could be either int or string so i solved my problem by combining two methods: GET api/fighters/1显然会导致错误,因为“ 1 ”可能是intstring所以我通过结合两种方法解决了我的问题:

// 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();
    }

}

this works however this doesn't feel right at all.这行得通,但这根本感觉不对。 What is the proper way to handle this problem?处理这个问题的正确方法是什么?

You can use route constraint您可以使用路线约束

[HttpGet("{id:int}")]
public async Task<ActionResult<Fighter>> GetFighter(int id) 

[HttpGet("{name}")]
public async Task<ActionResult<IEnumerable<Fighter>>> GetFighter (string name)

I had this problem in Core 3.0.我在 Core 3.0 中遇到了这个问题。 I finally found the solution was to put a route attribute on the action - eg [Route("NodeInfo")] .我终于发现解决方案是在动作上放置一个路由属性 - 例如[Route("NodeInfo")] That fixed it那解决了它

Please follow the solution for.Net Core 3.1 or higher Version:Use [Route("RouteName")]请按照.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}");
            }

        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 通过查询参数处理 .NET Core 3.1 Web API 中的多个端点 - Handle multiple endpoints in .NET Core 3.1 Web API by Query Params 如何正确创建 ASP.NET 内核 Web API - How to create ASP.NET Core Web API properly 我应该如何实现 REST API Controller 在 Z9E0DA8438E1E38A1C30F4B76CE7URIB8 中具有多个端点资源的核心资源? - How should I implement REST API Controller in ASP.NET Core for the resource that has multiple URI endpoints? 如何正确处理 ASP.NET Core MVC 中的 AJAX 错误? - How to properly handle AJAX errors in ASP.NET Core MVC? ASP.NET Core Web API:Z37A6259CC0C1DAE299ZA7866489DFFBD0如何处理? - ASP.NET Core Web API : how to handle null or empty parameters? 并发Web API请求以及如何处理ASP.NET Core中的状态 - Concurrent web api requests and how to handle state in ASP.NET core 所需建议/想法:如何通过ASP.Net Web API Core处理Nuxeo的身份验证和授权 - Suggestion/ideas needed: How to handle authentication and authorization for Nuxeo via ASP.Net Web API Core ASP.NET Core Web API - 如何处理 URL 查询字符串中的“null”与“undefined”? - ASP.NET Core Web API - How to handle "null" vs. "undefined" in URL query strings? Memory 缓存似乎在 Asp.Net Core Web Api 中的端点之间有所不同 - Memory cache seems to differ between endpoints in Asp.Net Core Web Api 如何从 ASP.NET Core Web API 返回 JSON,以便在浏览器中正确显示格式? - How to return JSON from a ASP.NET Core Web API, such that it's displayed properly formatted in the browser?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM