How To Create Simple Web API Using ASP.NET

In this article, we will learn how to create a simple example of a Web API using ASP.NET MVC. Before starting, we need to focus on the WebAPI definition.

"Web API is a framework which makes it easy to build HTTP services that reach a huge range of clients, including any type of browsers and mobile devices. Web API is a ptlaform for making RESTful services using .NET Framework."  


Never confuse  Web Services and WebAPI. Both are mainly used to create services, either REST or SOAP. In this part of the article, I'll use Visual studio 2012 MVC4 and WebAPI 1.

To create simple example of WebAPI, just follow the following steps.

Step 1

Create a project in VS2015 using MVC4 WebApi1.

Open Visual Studio, go to File=>New, and click on "Project". Thereafter, a new window will open to prompt you to select the template of VS.

 
Step 2

Select template "ASP.NET MVC 4 Web Aplication" and click OK. A new popup will open.

 

As per the above screen, there are a lot of templates available for building the application. But now, we are going to create WebAPI, so  click on "Web API".By default, the Home or Value Controller will open.

Step 3

Create a Controller "CSharp"=>"CSharpController". After creating a new API Controller, the Visual Studio Editor page will open. Here, we can write the code for API method as per our requirement.



In the above image, we can see that there is no extra configuration.

Step 4

Now, we are ready to create method. Just see the below code. In the following code example, I am getting the data from DB using Entity Framework.
  1. public HttpResponseMessage getdata(int ? id) {  
  2.     HttpResponseMessage response = new HttpResponseMessage();  
  3.     DB_DummyMVCEntities _dbcontext = new DB_DummyMVCEntities();  
  4.     var data = from c in _dbcontext.tbl_Employee  
  5.     where c.Id == id  
  6.     select c;  
  7.     if (data != null) {  
  8.         response = Request.CreateResponse(HttpStatusCode.OK, data);  
  9.     } else {  
  10.         response = Request.CreateResponse(HttpStatusCode.NotFound, "Data is empty");  
  11.     }  
  12.     return response;  
  13. }  
There are some important points that you should rememeber. 
  • I am using WebAPI 1 so here you can return HttpResponseMessage or can use own model, or list etc. But in WebAPI 2, there are IHttpActionresult.

  • I am not using any verbs like HTTPGET, HTTPPOST, etc. If you are not using any verbs, method can be called from clients by using the default GET.

  • In this example, I have used name "getdata(int? id)" and not using HTTPGET. It will be working fine but if you change the name of the method "getdata(int ? id)" to "data(int ? id)", that will not allow the call from any client. In that case, you have to set verbs attribute so that  the API assumes method name accordingly.
HttpresponseMessage

"HttpresponseMessage"
is used to return reponse from WebAPI. "Request.CreateResponse" is a helper method to create HttpResponseMessage object. Once you return an object, Web API has to serialize the object into response body in json format. Also, you can return you custom message with HTTP status code with data.

Step 5

Now, we can consume this WebAPI from any client using default routing as per MVC pattern. See the route pattern in the given code.
  1. public static void Register(HttpConfiguration config) {  
  2.     config.Routes.MapHttpRoute(name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new {  
  3.         id = RouteParameter.Optional  
  4.     });  
  5. }  
According to his pattern, our Endpoint will look like this - "Domain/api/CSharp/getdata/1" . Id is optional because I have used nullable parameter. If the parameter is not nullable, you will have to pass parameter value with end-point.

Complete endpoint - "http://localhost:54807/api,CSharp/getdata/1"

Step 6

Now, the Aeb API is ready to be consumed by any type of client. Just copy the endpoint and paste in Postman.

There are two ways to consume the endpoint,
  • http://localhost:54807/api/CSharp/getdata?id=1
  • http://localhost:54807/api/CSharp?id=1 

     
As per the above image, the data is coming in JSON format by default, but you can change it in XML according to your requirment. I hope you have learned a basic example of how to create WebAPI using default routing with WebAPI1 and without verbs. In the next artilce, we will learn Attribute routing with verbs using WebAPI1.

Some important links

Up Next
    Ebook Download
    View all
    Learn
    View all