Define Multiple GET Methods in WEB API

Multiple GET Methods in WEB API(2.0)

WEB API based on HTTP and used to expose data over HTTP. Every platform have HTTP libraries which are used to communicate with HTTP. using web api you can send and receive data over the HTTP. if you are already familiar with web API then you will face this problem that how you can define two GET or TWO post methods in single web api controller. This article will show you how you can achieve this goal by using Attribute Routing in web-api.

GET Started

Create a new MVC project and Select web-api from projects template. Now go to Tools->Library package manager->package manager console. and write fallowing command
Install-Package Microsoft.AspNet.WebApi.WebHost.
After installing build your project if you see any build error realted to Area->Help some .XML file then simply delete that file and build again.

Define Route

Now you need to define route for your controllers. open WebApiConfig.cs file from App_Start folder. and write fallowing code in void Register method

                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }

Register your configurations

Now write below line of code in Application_Start() method


Controller Code

Create a new controller in controller folder name it ProductController Now we define our controller which contains two GET methods. API will differentiate between both of these and return corresponding result.

    public class ProductController : ApiController
        public List ProductGET()
           List Dummyproductlist=new List();
           Dummyproductlist.Add("First product");
           Dummyproductlist.Add("Second product");
           Dummyproductlist.Add("Third product");
           return Dummyproductlist;
        public List Category()
            List Dummyproductlist = new List();
            Dummyproductlist.Add("First Category");
            Dummyproductlist.Add("Second Category");
            Dummyproductlist.Add("Third Category");
            return Dummyproductlist;

We define [RoutePrefix("api/Product")] for whole controller. so each method of this controller can be assessable by using api/Product/controllerName in application. after that we define Route[] for each controller. now when ever you call these methods you need to use their route names instead of actual methods names.

Build your application and run in browser. Write following URL in browser http://localhost:Your port number/api/Product/ProductGet your result will look like this
Multiple GET methods in api
Now change your URL to http://localhost:Your port number/api/Product/CategoryGET your result will look like this
Multiple GET methods in api