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
api/customers/
api/customers/13
/customers/currentMonth
/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
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.
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.
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" } ); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With