Wednesday, 28 August 2024

Creating ASP.NET Web API REST Service

 

What is ASP.NET Web API?

The ASP.NET Web API is one of the Microsoft open source technology to build the powerful REST Services which will communicate across all platform and devices over HTTP.

Let us implement it practically by creating one sample application.

Step 1. Create ASP.NET Web API Service.

  1. "Start", then "All Programs" and select "Microsoft Visual Studio 2015".
  2. "File", then "New" and click "Project", then select "ASP.NET Web Application Template" and provide the Project a name as you wish and click on OK, then the following windows will appear; select empty template and check on Web API as in the following image.
  3. Choose MVC empty application option and click OK.
  4. Now after adding the MVC project, the Solution Explorer will look like the following.

After creating the ASP.NET Web API project, the preceding folder structure and files are added into the project by default which are same as MVC project, so let us learn about them in brief as in the following.

  • App_Start folder:This folder contains the application configuration details such as routing, authentication, filtering of URL and so on.
  • Controller: This folder contains the controller and their methods. The controller is responsible for processing the user request and return output as a view.
  • Models: This folder contains the entities or properties used to store the input values.

Step 2. Create Model Class.

Right click on Model folder in the created Web API application, give the class name EmpModel or as you wish and click on OK.

Now write the following code into the EmpModel Class.

EmpModel.cs

public class EmpModel
{
    public string Name { get; set; }
    public string City { get; set; }
}
C#

Step 3. Add Web API Controller.

Right click on Controller folder in the created Web API application and Web API 2 Empty controller as in the following.

Now click on add and give the class name Home or as you wish and click OK as.

Now we have added Model class and web API controller class. Let's create the method into the HomeController class as in the following.

HomeController.cs

using System;
using System.Web.Http;

namespace CreatingWebAPIService.Controllers
{
    public class HomeController : ApiController
    {
        [HttpPost]
        public bool AddEmpDetails()
        {
            // write insert logic
            return true;
        }

        [HttpGet]
        public string GetEmpDetails()
        {
            return "Abhas Verma";
        }

        [HttpDelete]
        public string DeleteEmpDetails(string id)
        {
            return "Employee details deleted having Id " + id;
        }

        [HttpPut]
        public string UpdateEmpDetails(string Name, string Id)
        {
            return "Employee details Updated with Name " + Name + " and Id " + Id;
        }
    }
}
C#

In this above code we have created four methods for Insert, Update, Display and delete the records .The above web API controller methods defined with HTTP methods which are the following,

  • GET: Get the resource (Records) from particular source such as SQL database.
  • POST: Used to insert the records into the particular source such as SQL, Oracle database.
  • PUT: Used to modify the resource or records.
  • DELETE : Used to delete the specific resource or record from particular source.

Step 4. Run the application.

Now everything is ready lets run the application, it will throw the following error.

The reason of above error is we are not following the url structure which are set into the routing of web API application. The following is the default URL structure of ASP.NET Web API defined into the WebApiConfig.cs file.

From the above routing structure, we can access the resource using url format i.e Base url+api+apicontroller. Unlike MVC controller the web controller by default access all the methods just using controller name. Now our service is ready. Let's test it using REST client browser extension because browser only supports Get request directly from URL not others .

Our REST Service URL will be http://localhost:56290/api/Home which is described as follows.

  • http://localhost:56290: Is the base address of web API service, It can be different as per your server.
  • Api: It is the used to differentiate between Web API controller and MVC controller request .
  • Home: This is the Web API controller name.

Step 5. Testing Web API REST service using REST client.

Now let us test the application using REST client as.

POST

In the above image Web API REST Service, HTTP POST method returns the 200 Status code means REST service is successfully executed.

GET Method

In the above image Web API REST Service, HTTP GET method returns the 200 Status code means REST service is successfully executed and return the XML format output.

Note

  • The Web API REST service by default return the output as per browser default message header such as XML or JSON.

The above XML output return in Firefox browser., Now let's change the browser as IE, then output will return in JSON format as in the following,

From the above output its clear that output format by default depend on browser message format header.

Delete Method

In the above image Web API REST Service, HTTP Delete method returns the 200 Status code means REST service is successfully executed and return the XML format output. I hope from the preceding examples we learned how to create Web API REST Service.

Post Method Web API Example

 Insert new record in list.


This method add new employee in list and create response with success status and create URI for new record and add in header of response.

/// <summary>
///
 This Method add new record in list of employee.
/// and create response and allocate uri with id in header of response.
/// </summary>
///
 <param name="emp"></param>
/// <returns></returns>
public HttpResponseMessage PostAddNewEmployee(Employee emp)
{

     if (emp == null)
     {
         
throw new ArgumentNullException();
     }

    _emp.Add(emp);
     
var response = Request.CreateResponse<Employee>(HttpStatusCode.Created, emp);
     
string uri = Url.Link("DefaultApi"new { id = emp.Uid });
     response.Headers.Location = 
new Uri(uri);
      
return response;
}

Now In this step I will explain how to consume HTTP service Web API Post Method in Dot net.

Create a Resource (HTTP POST)

In this method set base address of Asp.Net Web API and sets the accept header to application/json that tells the server to send data in JSON Format.

PostAsJsonAsyn:This method serializes object into JSON format and send POST request to.

After that this method return Response object.

private static HttpResponseMessage ClientPostRequest(string RequestURI,Employee emp)
{
        
HttpClient client = new HttpClient();
        client.BaseAddress = 
new Uri("http://localhost:1379/");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
        
HttpResponseMessage response = client.PostAsJsonAsync(RequestURI,emp).Result;
        
return response;
}

Add This code to Main function of program.cs.->Add New Record in List of employee.

In this method create new employee and call above created method and pass employee object as a parameter then receive response from this method then call EnsureSuccessStatusCode method –This method throw exception when response status in not success.

After that check IsSuccessStatusCode true and false and return URL with Newly created employee ID.

//HTTP POST
Console.WriteLine("----------------Add New Employee -------------------");
Employee emp=new Employee(){ Uid=6,Name="Sikha",Address="Agra",City="agra"};
HttpResponseMessage responsePostMethod = ClientPostRequest("api/Employee",emp);
responsePostMethod.EnsureSuccessStatusCode();
if (responsePostMethod.IsSuccessStatusCode)
{
      
Uri empUrl = responsePostMethod.Headers.Location;
      
Console.WriteLine(empUrl.ToString());
}

After that you will run your application and see output.

output

Get Method Example Web API

 

Start with First Web API Project

Open Visual Studio (I am using Visual studio 2015) and from the File menu, select New and then click on the Project. It will open a New Project window.

start page 

I am using C#, so from the Installed Templates, choose the Visual C# node and under Visual C#, select Web. In the list of project templates, choose ASP.NET Web Application. Give the following name to the project, "WebApiSampleProject" and click OK. It will open a new ASP.NET Project dialog where you can select many types of template for the project.

new project 

In the new ASP.NET Project dialog, select the Empty template and check Web API. Click OK.

select template 

So, finally you have created a Web API project. It will create a default structure for the project.

solution explorer 

Add a model class

Model represents the data. It is an object of your data. The model contains all application logic such as business logic, validation logic, data access logic, etc. Web API can automatically serialize the model data to JSON, XML or some other format. The serialize data write into the body of HTTP response message. Client can access the data after de-serialization.

To add new model class, in the Solution Explorer, right click on the Models, select Add and Class.

add new model class 

It will open a dialog for Add New Item, select Visual C# node and select Class and give the proper name “Employee” for the model class and select Add. Modify the code for the model as below:

namespace WebApiSampleProject.Models
{
    public class Employee
    {
        public int EmployeeId
        {
            get;
            set;
        }
        public string EmployeeName
        {
            get;
            set;
        }
        public string Address
        {
            get;
            set;
        }
        public string Department
        {
            get;
            set;
        }
    }
}
C#

Add a controller

Web API Controller is responsible for handling all HTTP requests which can come from browser, mobile device, desktop web application or any other.

In Solution Explorer, right click the Controllers folder and select Add and then select controller. 

Add controller 

Note: Web API controller inherits the ApiController class instead of the Controller class.

It will open Add Scaffold dialog, select the Web API Controller - Empty template and click on Add.

Add scaffold 

In the Add Controller dialog, give a proper name to the controller, "EmployeeController" and click on Add.

Add controller 

You will see scaffolding creates an “EmployeeController.cs” class inside the controller folder.

Add two methods in the controller “GetAllEmployees” and “GetEmployeeDetails” and make dummy data for the Employee. See the following code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebApiSampleProject.Models;
namespace WebApiSampleProject.Controllers
{
    public class EmployeeController: ApiController
    {
        IList < Employee > employees = new List < Employee > ()
        {
            new Employee()
                {
                    EmployeeId = 1, EmployeeName = "Mukesh Kumar", Address = "New Delhi", Department = "IT"
                },
                new Employee()
                {
                    EmployeeId = 2, EmployeeName = "Banky Chamber", Address = "London", Department = "HR"
                },
                new Employee()
                {
                    EmployeeId = 3, EmployeeName = "Rahul Rathor", Address = "Laxmi Nagar", Department = "IT"
                },
                new Employee()
                {
                    EmployeeId = 4, EmployeeName = "YaduVeer Singh", Address = "Goa", Department = "Sales"
                },
                new Employee()
                {
                    EmployeeId = 5, EmployeeName = "Manish Sharma", Address = "New Delhi", Department = "HR"
                },
        };
        public IList < Employee > GetAllEmployees()
        {
            //Return list of all employees
            return employees;
        }
        public Employee GetEmployeeDetails(int id)
        {
            //Return a single employee detail
            var employee = employees.FirstOrDefault(e => e.EmployeeId == id);
            if (employee == null)
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
            }
            return employee;
        }
    }
}
C#

In the above controller you can see that the method “GetAllEmployees” return the list of all employees and the method “GetEmployeeDetails” returns the detail of single employee. See the following chart which shows how controller use route URL to perform action.

Controller MethodRoute URI
GetAllEmployees/api/employee
GetEmployeeDetails/api/employee/id

Run the Web API

To see the result, you can just create a client application which will use this web API or you can just simply press F5 or Ctrl+F5. It will open the browser with Url like http://localhost:53037/

To get all employees list, you need to make changes in the Url such as http://localhost:53037/api/employee.

To get the details of single employee, you need to pass the employee id in the Url http://localhost:53037/api/employee/4

Thanks for reading this article, hope you enjoyed it.