Single controller with multiple get methods in asp net web api

Introduction

ASP.NET is a popular language used for building web applications. One of the key features of ASP.NET is its ability to create APIs using the ASP.NET Web API framework. In this article, we will explore how to create a single controller with multiple GET methods in ASP.NET Web API.

Creating a Controller

To begin, let's create a new ASP.NET Web API project. Open Visual Studio and select “Create a new project”. Choose the ASP.NET Web Application template and select the Web API option. Click “OK” to create the project.

Once the project is created, you will see a default controller named “ValuesController” in the Controllers . This controller has a default GET method.

Adding Multiple GET Methods

To add multiple GET methods to the controller, we need to define additional methods with the [HttpGet] attribute. Let's say we want to add two additional GET methods: GetProduct and GetCategory.

[HttpGet]
public  GetProduct()
{
    return "This is the GetProduct method";
}

[HttpGet]
public string GetCategory()
{
    return "This is the GetCategory method";
}

In the above code, we have added two new methods: GetProduct and GetCategory. Both methods are decorated with the [HttpGet] attribute, which specifies that these methods be invoked when a GET request is made to the respective .

Routing

By default, ASP.NET Web API uses -based routing to map incoming to the controller and action method. In our case, the default for the ValuesController is “api/{controller}/{id}”.

To access the GetProduct method, we can make a GET request to “/api/values/getproduct”. Similarly, to access the GetCategory method, we can make a GET request to “/api/values/getcategory”.

Conclusion

In this article, we have learned how to create a single controller with multiple GET methods in ASP.NET Web API. By adding additional methods with the [HttpGet] attribute, we can define multiple endpoints for our API. This allows us to handle different types of GET requests and return the appropriate response.

Rate this post

Leave a Reply

Your email address will not be published. Required fields are marked *

Table of Contents