本文介绍了如何正确处理ASP.NET Core 3Web API中的多个端点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个处理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();
}

当我发送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会导致明显的错误,因为"1"可以是int也可以是string,所以我结合两种方法解决了这个问题:

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

}

这行得通,但是感觉一点也不对劲。处理此问题的正确方法是什么?

推荐答案

您可以使用route constraint

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

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

这篇关于如何正确处理ASP.NET Core 3Web API中的多个端点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 07:38
查看更多