Web API Get Method Example Asp.net

Get methods are for getting data from Web API, which allow API consumer to fetch data from API, now in one API we can have multiple Get methods, in this tutorial you will learn how to write different web API get method in asp.net 4.5 and asp.net Core 3.1 using C#.

public IEnumerable<string> Get()
{
    return new string[] { "value1", "value2" };
}

Once we create a webApi project, we can see there is a "ValuesController" created with two get methods

Now if you notice, the ValuesController is inherited from System.Web.Http.ApiController, when the HomeController in same folder is inherited from System.Web.Mvc.Controller

Web API Get Method Example

So, ValuesController is our WebApi controller, now let's look at get methods inside, One with parameter and another without parameter

public class ValuesController : System.Web.Http.ApiController            
{
    // GET api/values
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }
            
    // GET api/values/5
    public string Get(int id)
    {
        return "value";
    }
}

Take a look at the "App_Start/ WebApiConfig.cs" file, before you compile and run the default Web API

Note, In .net framework 4.5, apart from default get methods, if you want to create custom method names in Asp.net web API, you need to make changes in above route template of webApiConfig file (as shown in above picture).

route template should look like routeTemplate: "api/{controller}/{action}/{id}" in WebApiConfig file as example below.

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
		config.MapHttpAttributeRoutes();
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

Now you can create a custom method name GetAllStudents, and then access like http://localhost:9000/api/studentapi/GetAllStudents.

Default Get methods (.net framework 4.5 Web API)

After root it starts with “api/” then controller name, in this case "values", url may look like http://localhost:53207/api/values/

By default, the first get method will be executed, which will returns a string arrays

<ArrayOfstring xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<string>value1</string>
<string>value2</string>
</ArrayOfstring>

Now let’s call the second overload get with a integer parameter
Call may look like http://localhost:53207/api/values/5

<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">value </string>

Now in get method we can return any custom object (example "Client")

public Client Get(int id)            
{
    Client c = new Client() 
    { ClientId = 1, CompanyName = "TATA Capital", 
    ContactPerson = "Ratan Tata",
    Email = "ratantata@tata.com" };
            
    return c;
}

then we get result below, Remember if by default we get result in XML, when MediaTypeFormatter is XmlFormatter http://localhost:53207/api/client/5

<Client xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/WTRWebAPI">
<ClientId>1</ClientId>
<CompanyName>TATA Capital</CompanyName>
<ContactPerson>Ratan Tata</ContactPerson>
<Email>ratantata@tata.com</Email>
<Phone i:nil="true"/>
</Client>
When MediaTypeFormatter is JsonFormatter

But when MediaTypeFormatter is JsonFormatter, then the result will be JSON format

{"ClientId":1,"CompanyName":"TATA Capital","ContactPerson":"Ratan Tata","Email":"ratantata@tata.com","Phone":null}

Asp.net Core Web API GET Example

Here you learn how to write Web API Get method in Asp.net Core C#

In example below, I have written three Get methods in Student API, methods are Get, Get by Id and Get Collection.

Student Controller

Create a controller to provide all student related information.

[ApiController]
[Route("[controller]")]
public class StudentController : ControllerBase
{
}
Default Get Method

This is default get method, here in example I have returned one dummy student information, so that will help API consumer to understand the structure of student object.

public async Task<Student> Get()
{
    Student student = new Student();
    // get the student information from database.
    student.City = "City Name";
    student.Cotact = "Mobile Number";
    student.FirstName = "FirstName";
    student.LastName = "LastName";
    student.Email = "email@domain.com";
    return await Task.FromResult(student);
}
Get by Id Method

This method will return one single student information based on student id.

[HttpGet("{id}")]
public async Task<Student> Get(int id)
{
Student student = new Student();
// get the student information from database.
student.StuId = id;
student.City = "Kolkata";
    student.Cotact = "989200002";
    student.FirstName = "Avi";
    student.LastName = "Chakraborty";
    student.Email = "avi@domain.com";
    return await Task.FromResult(student);
}

There is another way to read data from FromQuery binding in get method, you can specify parameter name like public IActionResult SearchSomething([FromQuery(Name ="p1")]string pValue1)

Get Collection List Method

Creating custom method names in Asp.net Core Web API is super easy, here GetStudents is an example of custom method name.

The following method will return a collection list of student object , here in example i have hard coded some student information for testing purpose, you can replace that part with database code.

"GetStudents" is an example of asynchronous get method.
Notice, in attribute ResponseType, you should specify the same return type as defined in async method.

[Route("GetStudents")]
[HttpGet]
[ProducesResponseType(typeof(List<Student>),(int)HttpStatusCode.OK)]
public async Task<List<Student>> GetStudents()
{
List<Student> students = new List<Student>();
// get the student information from database.
students.Add(new Student() { City = "Kolkata", FirstName = "Anushka", StuId = 1 });
students.Add(new Student() { City = "Bangalore", FirstName = "Richard", StuId = 2 });
students.Add(new Student() { City = "Mumbai", FirstName = "Aniket", StuId = 3});
students.Add(new Student() { City = "Pune", FirstName = "Swami", StuId = 4 });
students.Add(new Student() { City = "Altanta", FirstName = "Janet", StuId = 5 });
return await Task.FromResult(students);
}

Above method will get you a list of students in json format by default.

 
Asp.Net Web API Get Example
Learn Web API: creating API using C# .Net, post, update, delete, read using .net API, set security, check authentication, testing.

C# web service interview questions

Learn API development
Asp.Net C# Web API Examples | Join Asp.Net MVC Course