Search code examples
c#asp.net-web-apiasp.net-web-api-routing

Routing with multiple Get methods in ASP.NET Web API


I am using Web Api with ASP.NET MVC, and I am very new to it. I have gone through some demo on asp.net website and I am trying to do the following.

I have 4 get methods, with the following signatures

public List<Customer> Get()
{
    // gets all customer
}

public List<Customer> GetCustomerByCurrentMonth()
{
    // gets some customer on some logic
}

public Customer GetCustomerById(string id)
{
    // gets a single customer using id
}

public Customer GetCustomerByUsername(string username)
{
    // gets a single customer using username
}

For all the methods above I would like to have my web api somewhat like as shown below

  • List Get() = api/customers/
  • Customer GetCustomerById(string Id) = api/customers/13
  • List GetCustomerByCurrentMonth() = /customers/currentMonth
  • Customer GetCustomerByUsername(string username) = /customers/customerByUsername/yasser

I tried making changes to routing, but as I am new to it, could'nt understand much.

So, please can some one help me understand and guide me on how this should be done. Thanks


Solution

  • From here Routing in Asp.net Mvc 4 and Web Api

    Darin Dimitrov has posted a very good answer which is working for me.

    It says...

    You could have a couple of routes:

    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
                name: "ApiById",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional },
                constraints: new { id = @"^[0-9]+$" }
            );
    
            config.Routes.MapHttpRoute(
                name: "ApiByName",
                routeTemplate: "api/{controller}/{action}/{name}",
                defaults: null,
                constraints: new { name = @"^[a-z]+$" }
            );
    
            config.Routes.MapHttpRoute(
                name: "ApiByAction",
                routeTemplate: "api/{controller}/{action}",
                defaults: new { action = "Get" }
            );
        }
    }