Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

//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):

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/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?

like image 383
merkithuseyin Avatar asked Sep 29 '19 16:09

merkithuseyin


People also ask

How do I resolve the issue the request matched multiple endpoints in .NET Core web API?

The solution is to disambiguate the paths. The two main options for doing that are 1) use route constraints or 2) change the paths to be different.

Can ASP.NET Core handle many requests?

ASP.NET Core apps should be designed to process many requests simultaneously. Asynchronous APIs allow a small pool of threads to handle thousands of concurrent requests by not waiting on blocking calls. Rather than waiting on a long-running synchronous task to complete, the thread can work on another request.

Can we have multiple get methods in web API?

As mentioned, Web API controller can include multiple Get methods with different parameters and types. Let's add following action methods in StudentController to demonstrate how Web API handles multiple HTTP GET requests.

What is an API endpoint in ASP NET Core?

Throttling Web API Endpoints in ASP.NET Core A web API endpoint is an interface for API consumers to interact with the server side application. Web API endpoints can provide data Extract, Transform, Load (ETL) services, cognition services, and other computing services.

How to consume third-party APIs in ASP NET Core?

The response of this API is the list of public holidays in JSON format as shown below: The most common and well knows class that allows us to consume third-party APIs in ASP.NET Core application is HttpClient class. This class gives us the ability to send HTTP requests to third-party APIs and receive HTTP responses returned from those APIs.

What are API endpoint rate limiting integration tests?

In the API endpoint rate limiting scenario, integration tests ensure that an API endpoint functions correctly through the request-response pipeline. ASP.NET Core supports integration tests using a unit test framework with a test web host and an in-memory test server.

What version of ASP NET Core is supported by the controller?

Swashbuckle.AspNetCore - Swagger tools for documenting APIs built on ASP.NET Core The below attributes show that versions 1 and 2 are supported by the controller class and also define a route including the version number Below MapToApiVersion attribute is showing what version number each of the actions supports.


2 Answers

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)
like image 71
Kahbazi Avatar answered Nov 11 '22 19:11

Kahbazi


I had this problem in Core 3.0. I finally found the solution was to put a route attribute on the action - e.g. [Route("NodeInfo")]. That fixed it

like image 20
Marshall Penn Avatar answered Nov 11 '22 18:11

Marshall Penn