Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 286
Yasser Shaikh Avatar asked Oct 08 '12 05:10

Yasser Shaikh


People also ask

Can we have multiple get methods in Web API?

As mentioned, Web API controller can include multiple Get methods with different parameters and types. Let's add following action methods in StudentController to demonstrate how Web API handles multiple HTTP GET requests.

Can we have multiple get methods in controller?

Usually a Web API controller has maximum of five actions - Get(), Get(id), Post(), Put(), and Delete(). However, if required you can have additional actions in the Web API controller.


Video Answer


1 Answers

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" }         );     } } 
like image 146
Yasser Shaikh Avatar answered Oct 16 '22 10:10

Yasser Shaikh