Implementing WEB API using ASP.NET MVC

Web API is a technology which follows HTTP REST Protocols. In short, we can also say that Web API is a programming interface to define Request and Response message system. It helps us to implement REST Principles. By doing the same it helps us to make our WEB Architecture simple. WEB API implements REST Architecture. Boththe client and server talk in terms of POST, PUT, DELETE, GET that simplifies our architecture. REST stands for Representation State Transfer.

Content Negotiation
 is a process where theserver identifies what type format the client supports and depending on that client format, the server sends the same format to him.diagram
                                                         WEB API Mechanism

As we know in HTTP, content negotiation is the mechanism that is being used in WEB API when facing several equivalent contents for a given URL, to provide the best suited on for the final user. The determination of the best suited content is made through one of the following three mechanisms:

  • Specific HTTP Header by the client (server driven negotiation)
  • The 300 Multiple choices or 406 Not Acceptable HTTP response codes by the server (agent driven negotiation)
  • A cache (transparent negotiation)

Server Driven Negotiation

In Server Driven Negotiation the browser sends several HTTP headers along with the URI, which are his preferred choice. The server than internally decides the best content to serve the client. In order to improve the algorithm choice user may include Accept: Header that specifies server that I understand these Headers.

Accept: Header

The Accept:
Header lists the MIME Types (Multi-Purpose Internet Mail Extensions).

Multi-Purpose Internet Mail Extensions

MIME type form a standard way of classifying file types on the Internet eg. text/html, audio/x-aiff, application/xml, text/xml, text/javascript etc. Internet programs such as Web Servers and browsers all have a list of MIME types, so that they can transfer files of the same type in the same way, no matter what operating system they are working in.

A MIME Type has two parts: a type and a subtype. They are separated by a slash(/) for ex. The MIME type of Microsoft words files is application and the subtype is msword, msexcel together the complete MIME is application/msexcel etc.

Coming back to Accept Headers, the Accept headers list the MIME type of media that the browser is willing to process. It is comma separated list of MIME types, each combined with a quality factor, as parameter gives the preference between different MIME sets.

The Accept Header is defined by the browser

Default Values:

Note that all browsers add the */* MIME Type to cover all cases. This is typically used for requests initiated via the address bar of a browser, or via an HTML <a> element.

Demonstrating */* MIME Type to cover all cases
               Demonstrating */* MIME Type to cover all cases


AGENT DRIVEN CONTENT NEGOTIATION

Server driven negotiation has some drawbacks.
  • To menu header for specifying to the Server.
  • Sending of the header must be done on every request.

HTTP allowed from the start another negotiation type, agent-driven negotiation.

A second problem is that one more request is needed in order to fetch the real resource, slowing the availability of the resource to the user. With agent driven the choice of the response is made once the server gets a response from the client.

TRANSPARENT CONTENT NEGOTIATION

Transparent content negotiation is a integration or combination of both server driven negotiation and agent driven negotiation. A transparent content negotiation is initiated by the agent by adding a Negotiate: header. This header tells the server that the client is supporting this type of negotiation. In its response, the server gives back the result of its server-driven content negotiation, i.e. the most-likely page according the Accept-*: headers sent by the agent in its request, and several HTTP headers indicating what alternative pages does exists. If the browser finds the alternatives more useful than the default page, it performs the second part a client-driven content negotiation and fetch the better page. That way, each time the server-driven content negotiation succeed only one HTTP request is needed, which is optimal. A second request is needed only when the Accept-*: header does not convey enough information to let the server do an optimal choice.

diagram
                                                             Flow of Request(text/html) and Response

  • Client sends the format type as a main type and sub type text/html, application/xhtml+xml, image/jpeg.
  • Main type is Text and Sub type is Html same for others.
    Main type is Application and Sub Type is xhtml, xml, etc.
  • As WEB Api supports Content Negotiation so we don’t have to return Action Result, Return JSON, etc. It automatically sends the supported format to the client.


Request Header
                                                                  Request Header

In the header we can see that chrome browser sends a message to the server that he understand text/html or application/xhtml+xml. So server sends back XML that he understands.

Let us start implementing the WEB API using ASP.NET MVC

Step 1. Start New Project

Start New Project

Step 1.1: Select MVC Project

Select MVC Project

STEP 1.2: Select WEB API

webapi

  • Delete all unnecessary files which are preloaded by Microsoft because we are going to make the project from scratch and preloaded files will make the project heavy.

  • First of all we need to add Entity Framework Dll, for this we need to Go to Nuget Manager and download the Entity Framework. Here are the steps.

  • We will be adding Dal (DATA ACCESS LAYER) class from where the data will be retrieved using entity Framework.

STEP 2: Go to Project and click on Manage Nuget Packages.

Nuget Packages.

STEP 2.1: Click on Nuget.org and write Entity Framework in search section.

search section

As the search criteria is complete we will see the page as shown above, we need to install the same. Click on I Accept and here we are ready to install Entity Framework as shown below.

install

Step 2.2: We have successfully installed Entity Framework and we ready to go and implement DAL Layer in our project.

DAL Layer

DAL Layer

Step 2.3: Now we will add a connection string to our program, for this we need to click on Server Explorer, then Add connection,

Add connection

And select the desired DB you want your application to access and click ok.

STEP 2.4: Right click on your connection and click Properties,

Properties

STEP 2.5: Copy the connection string,

connection

And go to web.config and change the connection string in Web.config file.

STEP 2.6

code

Please make sure that you name the string same as DAL class name, as in EF it’s necessary to have same name  as your class.

STEP 2.7

Now we are going to add a new project which will be our Model(class) that contain all properties as the db table column.

table

Add reference of System.componentModel.DataAnnotations and define a key over your property as EF need a key else you will face the following error:

code

code

connection

Coming back to our DAL class we will now add the DBset object which going to hold the information related to DB.

For this add reference of Customer Model in DAL,

dal

Now in DAL class we need to use Customer Model namespace so that we can map DBset object to correspond to table in the database.

Now in Data Access Layer we create a DBset. Properties of Class Customer will give us Customer Objects.

  1. public DbSet < Customer > Customers   
  2. {  
  3.     get;  
  4.     set;  
  5. }  
This line means that the class will return a collection of Customer class, whenever we want to emit out the objects of the class it is type of DbSet.

Now the question comes how Entity framework maps the Customer class with Details Tables so for this we need to give mapping.

ORM Tool Mapping
                                                     ORM Tool Mapping

ORM Tool Mapping

Customer Class is going to be mapped with table details. So now we have mapped our classes, let us start with our Web API.

STEP 3: Creating a web Api controller

Now we will create a Customer Controller which will contain all REST HTTP method of class Customer,

controller

In place of selecting MVC 5 controller we need to select Web API Controller, press Add and now we are ready to work with WEB API.

controller

controller

Now we will see that in WebApi, the Contoller inherits ApiContoller class, while in MVC it inherits from Contoller class. Now this ApiContoller class helps follow the HTTP REST principle. Now we are going to implement REST principles. We would implement http methods referred as Verbs indicating the desired action to be performed.

 GET  FETCH A RESOURCE
 PUT  UPDATE A RESOURCE
 DELETE  DELETE A RESOURCE
 POST  APPEND OR ADD A RESOURCE

STEP 3.1: Adding Customer Class and DAL class reference in WEB Api,

api

Now we are going to create a Get method to get all details from table.

STEP 3.2: Creating a object of dal class and accessing the DBSET Customers,

using System.Data.Entity; namespace


namespace

Now we will go to WebApiConfig file, 

webapi

And now in Global.cs file we have to add if not,

presentGlobalConfiguration.configure(WebApiConfig.Register);

code

Now in WebApiConfig file we can see the routing for web api is like,
  • API/{CONTROLLER}/ID
  • API/CONTROLLER NAME/
Now add Entity framework dll in web api. So now just checking whether our Get method is firing or not we will execute our program and write the following url,

dll

Now run your WEB API and write http://localhost:20656/api/Customer in browser. I have put a debug point in program to see how the data flows.

dataflows
  • Data access layer object is created using DBset which return the listlist of customer.
  • Here instead of returning a view, content we are just returning a list because of content negotiation as discussed before it automatically gives the desired data to agent or client as per his understanding (xml, json, xhtml, html, etc.)

Now, I am right now executing this in Google Chrome and received the following output:

xml

That is a XML Format, as I have discussed earlier that in chrome it sends Request Header as text/html, application/xhtml+xml,application/xml etc), so application returned xml.

cutomer

Lets try the same in Internet Explorer,

As we input the url we will receive the following dialog box and while opening the file in notepad.

windows

code

We will find that JSON format is returned of the list. So we can fairly see how the Web Api follows Content Negotiation.

STEP 4:

Now we will go ahead and write the code for REST based Http Methods i.e. Post, Get, Put, Delete.

POST:
 The POST method is used to request that the server accept the data send enclosed in the request.

post

PUT: The PUT method requests that the enclosed entity be stored under the supplied Request-URI.

put

GET:

The GET method means retrieve whatever information (in the form of an entity) is identified by the Request-URI.

get

DELETE: 

The DELETE method requests that the server to delete the resource identified by the Request-URI. .

delete

Now we will go ahead and consume our WEB API methods using MVC and see how the WEB API follows REST Principle and returns the data in a simple way.

STEP 5:

Now I order to consume these HTTP methods we need to have a Controller and User Interface.So now add Controller and add MVC5 Empty controller and name it as CustomerMVCController as shown below.

controller

controller

controller

So now we will create a view which we will implement all HTTP methods.

view

And write below html code for a UI .

code

As the Name specifies we will be performing “POST” method by btnSubmit, “DELETE” method by btnDelete vice versa.

Now in the Routes.config I made a new route so that when the project run it will by default hit the CustomerMVC Controller and its action method Index.

code

Now we will call the API method using Ajax, so in order to do that we will use jQuery events and based on the click event of button we will perform the corresponding method calls, for that we need to refer JQuery first, as the referring part is done we will go ahead to achieve our goals.

POST

In all JavaScript method when ajax call the api method once the call is successful it permits us to call a function which you want to call, so we have called OnSuccess method which will receive the collection of data and at runtime we will perform a for loop and will add the list of tr and collection of data to the table, by default we set display:none for the table as shown below.

code

code

code

DELETE

code

PUT

code

GET


code

Now once we are done with coding and designing phase lets begin and execute our application step by step.

View

view

Now as the options are available to the user to perform the CRUD operations. We will first start with Submit which means we are posting some data to the server.

In order to check the application and data flow I have put debugger in JavaScript and breakpoints in my C# code. So press ctrl+shift+i to open the developer mode of Chrome or F12 for IE. Before moving ahead just want to let you know that I have not created any validation logic in jQuery or Server side validation using Data Annotation.

So user now inserts the data as shown below,

code

And we can see in debugging mode that after storing the values of the textbox ajax will call the POST action method to the url “api/Customer”, once data flows ahead and hit is made to our web Api POST method as in the following figure:

code

The POST method will post the data to the server and store the same, then return back the list of Customer and display it to the View, as shown below.

webapi

Now I will be inserting more records so that there will be a collection of records, after inserting 5 records we can see below how the data is returned and shown in the view.

webapi

Now once the Post HTTP method has been successfully accomplished we will be performing Delete Method, we will just input the UserName and Password and the same data get deleted from the database. If user inputs “ankit” and “negi” and press on delete, the DELETE web api method will be call because we want resource to be removed from the DB.

code

Now the Delete api method is hit and deletion of resource is performed and the list of objects after resource deletion are returned to the View.

view

You can see in below mentioned figure “Ankit” “Negi” has been deleted from the server.

webapi

Now in order to perform PUT method (update) I have made a validation that once the user input updates application will ask for new password and the same will PUT to the server. We will see this as we go ahead in the article.

User Clicks on update and he/she will prompted with alert to enter the new password and text of Password will be changed to New Password.

webapi

Now after collecting the new data given by the User, the application will call the PUT method because we want to update a Resource and after updating the resource the list of Customers will be send to the view.

code
code

After Updating: 
The returned list,

list

Now the last and the final call is for GET:FETCH A RESOURCE.

Here we will be fetching all the records, the user just presses the Show button and GET method is hit of Web Api and all the records are displayed to the View.

Ajax will call the api/Customer Get method and hit will come to GET method.

code

And all the records are returned to the view.

code
webapi
I hope this article will be helpful to understand the concept of WEB API.

I want to add on one more point to this article, which is passing soap requests and gettinga soap response back with the help of Web API.

Here I am not going to create any webpage, rather I will try to execute the request via Postman. Postman is a widget of Chrome which helps us to work with API. Let’s get started:
  • Download Postman from

    postman

  • Setting Up post man request,

    I will try to demonstrate the Post Request through Postman using xml format.

    xml

  • Post: Specifies the action
    Content-type specifies the type of the content to be passed i.e. xml.

    xml

    Body specifies the xml request.

Now in Web ApiConfig add the following lines:

  1. Config.Formatters.XmlFormatter.UseXmlSerializer = true;  
XMLSerializer provide us more strong control over the resulting XML format and it will be needed if we need to generate the serialized XML in a predefined/ existing format.
 
Let us try to hit a request to the API as shown below:

Request:

request

Request hits the Post method of API.

code

Response:

code

I hope this article was helpful. Keep learning and sharing.

Up Next
    Ebook Download
    View all
    Learn
    View all