Get Single Resource in Asp.Net Web API

In my previous article, we discussed how to fetch data in Asp.Net Web API. Today we discuss how to get a single resource based on query string values.

Considering the same example, we fetch the single employee data based on its id, as shown below.

//GET: Employee based on id
[Route("api/employees/getemployee")]
[HttpGet]
public HttpResponseMessage GetEmployee(int id)
{
      try
      {
           //int id = 1;
           return Request.CreateResponse(HttpStatusCode.OK, Company.GetEmployee(id));
       }
       catch (Exception ex)
       {
                return Request.CreateResponse(HttpStatusCode.InternalServerError, ex);
         }
}

Here we have declared the URI as api/{controller}/{actionMethod}. We have to pass id through the query string. Run the application and change the URL as https://localhost:44358/api/employees/getemployee?id=1, and it displays employee details whose id is “1” as shown below.

We can add more than one parameter also like below.

//GET: Employee based on id and name
[Route("api/employees/getemployee")]
[HttpGet]
public HttpResponseMessage GetEmployee(int id, string name)
{
        try
        {
             //int id = 1;
              return Request.CreateResponse(HttpStatusCode.OK, Company.GetEmployee(id, name));
          }
          catch (Exception ex)
           {
                return Request.CreateResponse(HttpStatusCode.InternalServerError, ex);       }
}

Here we added one more parameter name to the request. Run the application and change the URL to https://localhost:44358/api/employees/getemployee?id=1&name=John, and it displays the output as shown below.

                                                                                   CompanyRestAPI-2.zip (55.60 mb)