ASP.Net Web API 2

tudip-logo

Tudip

17 January 2020

Objective:

In this article, we will see the basics of ASP.NET Web API. We will try to understand what is the Web API, what is the basic structure of a ASP.NET Web API project, the difference between the Web API and MVC, use of filters, routing and different hosting modes. Also, We will create a simple application to demonstrate the CRUD operation in Web API.

Background:

Initially, on the transformation of the application from Desktop to Web the major accelerator was HTTP, originally shipped with Internet Explorer 5, which uses the JavaScript that allows web developers to communicate back from the browser to the server.

ASP.NET Web API, first introduced in 2011, which is HTTP-centric programming model. The next version Web API 2 is shipped with MVC 5.

Definition:

The ASP.Net Web API is a framework designed for web developers for building HTTP services which can be consumed by clients including browsers base or handheld devices. As, it is very similar to ASP.NET MVC because it contains the MVC features such as routing, controllers, action results, filter, model binder, dependency injection. But the ASP API is not a part of the MVC Framework. It is a part of the core ASP.NET platform which can be used with MVC or any other types of Web applications. It is a stand-alone Web services application.

How it is different from MVC:

  • Asp.Net MVC returns both views and data but Asp.Net Web API returns only data.
  • Web API also takes care of returning in JSON, XML or any other. MVC only returns data in JSON format.
  • In Web API the requests are mapped to the actions based on HTTP verbs but in MVC it is mapped to the actions name.
  • Asp.Net Web API is a framework and part of the ASP.NET framework. The model binding, filters, routing and other MVC features in Web API are different from MVC. In MVC, these features exist within System.Web.Mvc.
  • You can mix Web API and MVC controller in a common project to handle AJAX requests which may return data in JSON, XML.
  • To mix MVC and Web API controller and then for Autorisation you have to create two filters one for MVC and another for Web API as both are different.

Start with the Web API:

The ASP.NET MVC 5 ships as part of Visual Studio 2013 and in Visual Studio 2012 as an addon. You can create a sample project in any version after 2012 using File => New => Project.

asp.net-1

Select the ASP.Net web application and then we need to select the project type as Web API.

asp.net-2

The project not only includes the Web API will provide you a sample API controller (called ValuesController) and some MVC code that can automatically generate help pages for your Web APIs for the reference.

asp.net-3

Request and response data types supported:

  • Incoming
    You can put parameters on your action, and just like MVC (in request body or in the URL), the Web API will automatically provide values for those action parameters.
  • Return type
    Web API can return HttpResponseMessage to represent the response to send back to the client it can be the success or exception. The API will automatically convert the returns into a structured response like JSON or XML. There are few in build responses are provided by the API Controller like:

    • Conflict
    • Redirect
    • Response Message
    • Unauthorized
    • RedirectToRoute

Basic configuration in the Web API:

  • Configuring the route:
    The class that the route contains the information for action. One if RouteConfig.cs which will contain the default normal route of the application. Another is the WebApiConfig.cs, contains the routing for the WebAPI controllers.asp.net-4
  • Configuring the filter:
    We can apply filters at the action level, at the controller level and at the configuration level as well. For the global level exceptions, we need to configure the FilterConfig file.asp.net-5
  • Configuration of hosting:
    So there are two ways we can host a WebApi:
    • IIS Hosting – Hosting a WebApi inside ASP.NET application.
    • Self hosting – Have our own application host the ASP.NET WebApi

Web API repository pattern:

Following is an example of how to retrieve and insert data using Web API 2.

asp.net-6

Code Base:

  • View Model
    public class EmployeeViewModel
    
        {
    
            public int ID { get; set; }
    
            public string Name { get; set; }
    
            public string Address { get; set; }
    
            public string Phone { get; set; }
    
        }
  • Interface:
    public interface IGenericDetails
    
        {
    
            IEnumerable GetAll();
    
            IEnumerable GetByID(int id);
    
            bool Insert(EmployeeViewModel  model);
    
            bool Update(EmployeeViewModel model, int id);
    
            bool Delete(EmployeeViewModel model, int id);
    
         }
  • Controller
    public class EmployeeController : Controller
    
        {
    
            IGenericDetails r_Obj = new EmployeeDetails();
    
    
            [HttpGet]
    
            [Route("api/Employee/get")]
    
            public IEnumerable<EmployeeViewModel> Get()
    
            {
    
                var details = r_Obj.GetAll();
    
                return details;
    
            }
    
    
            [HttpGet]
    
            [Route("api/Employee/GetDetailsByID/{id}")]
    
            public IEnumerable<EmployeeViewModel> GetDetailsByID(int id)
    
            {
    
                var details = r_Obj.GetByID();
    
                return details;
    
            }
    
    
            [HttpGet]
    
            [Route("api/Employee/AddEmployee")]
    
            public IHttpActionResult AddEmployee(EmployeeViewModel model)
    
            {
    
                try
    
                {
    
                    e_Obj.Insert(model);
    
                    return Ok("Success");
    
                }
    
                catch(Exception ex)
    
                {
    
                    return BadRequest(ex.Message);
    
                }
    
            }
    
        }
  • Repository
     public class EmployeeloyeeDetails : IGenericDetails
    
        {
    
    
            ApiDBEntities db = new ApiDBEntities();
    
    
            public IEnumerable GetAll()
    
            {
    
                var items = db.DetailsRepository.Select(i =>
    
                           new EmployeeViewModel { ID = i.ID, Name = i.Name, Address = i.Address, Phone = i.Phone });
    
                return items.ToList();
    
            }
    
    
            public IEnumerable GetByID(int id)
    
            {
    
                var result = db.DetailsRepository.Where(i => i.ID == id).Select(i =>
    
                             new EmployeeViewModel {ID = i.ID, Name = i.Name, Address = i.Address, Phone = i.Phone});
    
                return result.ToList();
    
            }
    
    
            public bool Insert(EmployeeViewModel dt)
    
            {
    
                DetailsRepository obj = new DetailsRepository();
    
                obj.Name = dt.Name;
    
                obj.Address = dt.Address;
    
                obj.Phone = dt.Phone;
    
                db.DetailsRepository.Add(obj);
    
    
                var Result = db.SaveChanges();
    
                if (Result == 1)
    
                {
    
                    return true;
    
                }
    
                else
    
                {
    
                    return false;
    
                }
    
            }
    
    }

Request a quote