I am using ASP.NET Web API. There is a Users Controller with the following two methods.
[HttpGet("{firstName}")]
public List<string> GetByFirstNameContains(string firstName)
{
return new List<string>()
{
"F1", "F2", "F3"
};
}
[HttpGet("{lastName}")]
public List<string> GetByLastNameContains(string lastName)
{
return new List<string>()
{
"L1", "L2", "L3"
};
}
The following error is generated:
Microsoft.AspNetCore.Routing.Matching.AmbiguousMatchException: The request matched multiple endpoints. Matches:
GettingStartedAPI.Controllers.UsersController.GetByFirstNameContains (GettingStartedAPI)
GettingStartedAPI.Controllers.UsersController.Get (GettingStartedAPI)
GettingStartedAPI.Controllers.UsersController.GetByLastNameContains (GettingStartedAPI)
at Microsoft.AspNetCore.Routing.Matching.DefaultEndpointSelector.ReportAmbiguity(Span1 candidateState) at Microsoft.AspNetCore.Routing.Matching.DefaultEndpointSelector.ProcessFinalCandidates(HttpContext httpContext, Span
1 candidateState)
at Microsoft.AspNetCore.Routing.Matching.DefaultEndpointSelector.Select(HttpContext httpContext, Span`1 candidateState)
at Microsoft.AspNetCore.Routing.Matching.DfaMatcher.MatchAsync(HttpContext httpContext)
at Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.Invoke(HttpContext httpContext)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context)
Is there a way to have multiple methods in the same controller that will search by different fields?
This also falis:
[HttpGet("{id}")]
public string Get(int id)
{
return "value";
}
[HttpGet("{lastName}")]
public List<string> ArgleBargle(string lastName)
{
return new List<string>()
{
"L1", "L2", "L3"
};
}
Microsoft.AspNetCore.Routing.Matching.AmbiguousMatchException: The request matched multiple endpoints. Matches:
GettingStartedAPI.Controllers.UsersController.Get (GettingStartedAPI)
GettingStartedAPI.Controllers.UsersController.ArgleBargle (GettingStartedAPI)
I constructed the following hideous monstrosity, which kind of works. Obvioudly, there must be a better way. Any help would be greatly appreciated.
[HttpGet("{field},{value}")]
public dynamic Get(UserNameFields field, string value)
{
if (field == UserNameFields.FirstName)
{
return new List<string>()
{
"F1", "F2", "F3"
};
}
else if (field == UserNameFields.ID)
{
return "value";
}
else
{
return new List<string>()
{
"L1", "L2", "L3"
};
}
}