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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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}";
        }
    }
}
comments powered by Disqus

Related