ASP.NET 5 Web Api Controller with multiple get methods

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.

  • 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 web services, 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.

 1using Microsoft.AspNet.Mvc;
 2
 3namespace ControllerWithMultipleGetMethods.Controllers
 4{
 5    [Route("api/[controller]")] /*  this is the default prefix for all routes, see line 20 for overriding it * / 
 6    public class ValuesController : Controller
 7    {
 8        [HttpGet] // this api/Values
 9        public string Get()
10        {
11            return string.Format("Get: simple get");
12        }
13
14        [Route("GetByAdminId")] /*  this route becomes api/[controller]/GetByAdminId * /
15        public string GetByAdminId([FromQuery] int adminId)
16        {
17            return $"GetByAdminId: You passed in {adminId}";
18        }
19
20        [Route("/someotherapi/[controller]/GetByMemberId")] /*  note the / at the start, you need this to override the route at the controller level * /
21        public string GetByMemberId([FromQuery] int memberId)
22        {
23            return $"GetByMemberId: You passed in {memberId}";
24        }
25
26        [HttpGet]
27        [Route("IsFirstNumberBigger")] /*  this route becomes api/[controller]/IsFirstNumberBigger * /
28        public string IsFirstNumberBigger([FromQuery] int firstNum, int secondNum)
29        {
30            if (firstNum > secondNum)
31            {
32                return $"{firstNum} is bigger than {secondNum}";
33            }
34            return $"{firstNum} is NOT bigger than {secondNum}";
35        }
36    }
37}
comments powered by Disqus

Related