I have two other posts on multiple GET methods, both for Web Api 2, the first shows how to use routes like ‘http://…/api/values/geta’ and the second shows ‘http://…/api/values/22’ or ‘http://…/api/values/AAC1FB7B-978B-4C39-A90D-271A031BFE5D’.
I was recently working on a Asp.Net 5 Web.Api application and needed a controller with multiple get methods.
I wanted to have something like GetByAdminId(int adminId) and GetByMemberId(int memberId) (yes I know people will say that you should have two controllers and maybe even two webservices, but that is the scenario I was faced with).
Of course this should not be the most difficult problem, but it was not obvious either.
Here is the solution.
using Microsoft.AspNet.Mvc; namespace ControllerWithMultipleGetMethods.Controllers { [Route("api/[controller]")] /* this is the default prefix for all routes, see line 20 for overriding it */ public class ValuesController : Controller { [HttpGet] // this api/Values public string Get() { return string.Format("Get: simple get"); } [Route("GetByAdminId")] /* this route becomes api/[controller]/GetByAdminId */ public string GetByAdminId([FromQuery] int adminId) { return $"GetByAdminId: You passed in {adminId}"; } [Route("/someotherapi/[controller]/GetByMemberId")] /* note the / at the start, you need this to override the route at the controller level */ public string GetByMemberId([FromQuery] int memberId) { return $"GetByMemberId: You passed in {memberId}"; } [HttpGet] [Route("IsFirstNumberBigger")] /* this route becomes api/[controller]/IsFirstNumberBigger */ public string IsFirstNumberBigger([FromQuery] int firstNum, int secondNum) { if (firstNum > secondNum) { return $"{firstNum} is bigger than {secondNum}"; } return $"{firstNum} is NOT bigger than {secondNum}"; } } }
This is a great solution I have been looking for! It’s working as a charm!
Glad it helped you 🙂
Sweet jumping Jesus! The prefix of a slash was killing me. Thank you so much!
Glad it helped you, you are probably the happiest reader I’ve had.
Pingback: Web API 2 Controller with multiple get methods | no dogma blog
Pingback: Web API 2 Controller with multiple GET methods – part 2 | no dogma blog
can you provide the code of the http requests you are making to access this controller
I don’t understand what you are asking. The requests are usually made with a web browser or Fiddler.
Do you need to change WebApiConfig.cs or something for route configuration? It does not work for me now.
Take a look at the zip file, it has all the source code.
Where is zip file?
It looks like I forgot to include it, and I don’t have the original source code now, sorry.