Get Data using Asp.Net Rest Web API

In my previous articles, we discuss Rest API basics. Today we discuss how to get data by using Asp.Net Web Rest API. Here we are using Microsoft Visual Studio 2019 for development.

Open Visual Studio 2019 => Create New Project => Search for “Asp.Net Web Application (.Net Framework)” in C#. Here we are using .Net Framework only not Asp.Net Core.

Enter the project name as “CompanyRestAPI” and click on the Create button. Select the Empty project & Web API checkbox, as shown below, and click on the Create button.

Here we are trying to fetch the employee details from the Company database through Entity Framework. I am not focusing on the data access part, concentrating only on Asp.Net Web API logic.

Right Click on the project Controller folder and select Add Controller. Select the Empty controller, as shown below. 

Import System.Web.Http package through NuGet and change inherited class from Controller to ApiController. Delete Index() method and add the GetEmployees() method, as shown below.

using System;
using System.Net;
using System.Net.Http;
using System.Web.Http; 

namespace CompanyRestAPI.Controllers
{
    public class EmployeesController : ApiController
    {
        // GET: Employees
        public HttpResponseMessage GetEmployees()
        {
            try
            {
                return Request.CreateResponse(HttpStatusCode.OK);
            }
            catch(Exception ex)
            {
                return Request.CreateResponse(HttpStatusCode.InternalServerError, ex);
            }
        }
    }
}

As shown above GetEmployees() method is returning HttpStatusCode.Ok (status code 200) in try block and HttpStatusCode.InternalServerError (status code 500) in catch block. That means we are returning Success status code (200) to the client if there are no errors and Internal Server Error (500) if any error occurs.

Run the application (for me URL is https://localhost:44358/); it shows error as “HTTP Error 403.14 – Forbidden” because we have configured our controller route as api/{controller} in WebApiConfig.cs class, as shown below.

using System.Web.Http; 

namespace CompanyRestAPI
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            // Web API routes
            config.MapHttpAttributeRoutes(); 

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

As shown above, we have set the routeTemplate value as “api/{controller}/{id}”. Here controller is the name of the controller class, and id is the parameter that needs to pass to the controller. We have to define the controller action method with the HttpGet verb, but by default, it returns the Get() action method only. Change the URL to https://localhost:44358/api/employees; it displays empty data because our GetEmployees() action method returning no data. Change the GetEmployees() action method to return some data, as shown below.

public HttpResponseMessage GetEmployees()
{
            try
            {
                return Request.CreateResponse(HttpStatusCode.OK, Company.GetEmployees());
            }
            catch(Exception ex)
            {
                return Request.CreateResponse(HttpStatusCode.InternalServerError, ex);
            }
}

As shown above, the Company.GetEmployees() method getting all employee details. Now run the application, and it displays the output as shown below.

By default, Asp.Net Rest API returns the data in XML format. As shown in the code, we didn’t configure the URI name for GetEmployees() method, but still, it is returning data without mentioning its name in the URI (https://localhost:44358/api/employees) because we have only single Get method here. It is very difficult if we have multiple methods, so let’s configure the URI for our GetEmployees() method, as shown below.

        // GET: Employees
        [Route("api/getemployees")]
        [HttpGet]
        public HttpResponseMessage GetEmployees()
        {
            try
            {
                return Request.CreateResponse(HttpStatusCode.OK, Company.GetEmployees());
            }
            catch(Exception ex)
            {
                return Request.CreateResponse(HttpStatusCode.InternalServerError, ex);
            }
         }

As shown above, we mentioned the HttpGet verb and route for the GetEmployees() method. Run the application, https://localhost:44358/api/employees URI will not work because we have mentioned a different route for our action method. Change URI to https://localhost:44358/api/getemployees, which displays the data. If we don’t declare HttpGet verb, our action method should start with Get like GetEmployees().

Here we are fetching all employees; in my next article, we discuss how to fetch single employee data based on employee id.

                                                                                                                       CompanyRestAPI.zip (55.59 mb)