Skip to main content

Your First ASP.NET Web API in Action.

ASP.NET Web API is a framework for building Web APIs on top of the .NET Framework. In this tutorial, we’ll create a web API in ASP.Net to become familiar with Web API.

So let’s start J

Open Visual Studio IDE > Create New Project > Under Web Template > Select ASP.NET MVC 4 Web Application > and provide a name (in this case TestWebAPI) and select the location.


On next screen select “Web API” under template and click OK.


Your default WebAPI project is created and ready for use; let’s have a look on file and directories of default project.


Folders
Description
App_Data
This folder contains application data files.
App_Start
Contains different configuration files
Content
All the themes and styles files are added under this folder.
Controllers
Conations Web API controllers
Images
Contains Images of the project
Models
Models folder used to create Model under it, by default there is no Model.
Scripts
All the client script files located under this folder.
Views
All the MVC views located under this, by default you can see some views as well.
Beside that there is Web.Config and Global.asax files.

We have understood the directory structure, now we’ll create a simple WebAPI.

Add a Model:
A model is nothing but a class file having properties that represents the data in your application. ASP.NET Web API can automatically serialize your model to JSON, XML, or some other required format, and then write the serialized data into the body of the HTTP response message.

Let's create a simple model for Customers > Right-click the Models folder and add a new Class and add four properties in class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace TestWebAPI.Models
{
    public class Customer
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public string City { get; set; }
    }
}

Add a Controller
A controller is an object that handles HTTP requests. If you are ASP.NET MVC developer, then you are already familiar with controllers. But controller in Web API derives from the ApiController class instead of Controller class. Another major difference is that actions on Web API controllers return data instead of views.

Under Controllers folder, by default there are two controllers:
·         HomeController is not directly related to Web API and it is an ASP.NET MVC controller.
·         ValuesController is an example Web API controller with empty read/write actions.

Let’s delete ValuesController, and then add new controller as follows:

Right-click on the Controllers folder > Select Add and then select Controller > Enter controller name (i.e. CustomerController in this case) and select a template, there are different options available there, we’ll go with Empty API controller.


Now our Controller is ready to use, open this controller and replace the code in this file with the following:

using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web.Http;
using TestWebAPI.Models;

namespace TestWebAPI.Controllers
{
    public class CustomerController : ApiController
    {
        List<Customer> customers = new List<Customer>
        {
            new Customer {Id=1, Name = "Sandeep Kumar", Email = "sandeep@test.com", City = "Gurgaon" },
            new Customer {Id=2, Name = "Customer1", Email = "customer1@test.com", City = "Gurgaon" },
            new Customer {Id=3, Name = "Customer2", Email = "customer2@test.com", City = "Gurgaon" },
            new Customer {Id=4, Name = "Customer3", Email = "customer3@test.com", City = "Gurgaon" },
            new Customer {Id=5, Name = "Customer4", Email = "customer4@test.com", City = "Gurgaon" }
        };

        public IEnumerable<Customer> GetCustomers()
        {
            return customers;
        }

        public Customer GetCustomerById(int id)
        {
            var customer = customers.FirstOrDefault(c => c.Id == id);

            if (customer == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            return customer;
        }
    }
}

In this controller class we have used a fixed list of Customer; you can get it from DB or any other external data source as per your convenience.

The CustomerController defines two methods that return customers:

·         The GetCoustomers method returns all the customers.
·         The GetCustomerById method returns a single customer by its Id.

So now we have a fully functional Web API ready for use, each method on the controller maps to a URI through which we can access our API by sending an HTTP GET request:

Controller Method
Mapping URI
GetCoustomers
/api/customer
GetCustomerById
/api/customer/id

Let’s see Web API in action now, run the application, and by default it’ll open default page.

Access Web API with mapping URI mentioned above to see the result.


All Customers
customer by Id 
That’s it for now; you can also download sample code of this post from.

In the next article we’ll call our Web API methods with the help of JQuery.

Popular posts from this blog

C#: Merging Excel cells with NPOI HSSFWorkbook

In this post we’ll see how to merge the two or more cell with each other while creating the excel sheet using NPOI.
Mentioned below is code to merge multiple cells, in this example we are merging first cell to fifth cell of first row (you can adjust row or cell range by passing particular parameters in CellRangeAddress).
//Created new Workbook var hwb = new NPOI.HSSF.UserModel.HSSFWorkbook(); //Create worksheet with name. var sheet = hwb.CreateSheet("new sheet"); //Create row and cell. var row = sheet.CreateRow(0); var cell = row.CreateCell(0); ; //Set text inside cell cell.SetCellValue("This is Merged cell"); cell.CellStyle.WrapText = true; //define cell range address // parameters: -> first row to last and first cell to last cell var cra = new NPOI.SS.Util.CellRangeAddress(0, 0, 0, 4); //Add merged region to sheet. sheet.AddMergedRegion(cra);
Hope this solution helps you J

Difference between Web API, WCF and Web Service

So now we have got the basic idea about Web API, now let’s do some comparison of Web API with WCF and web services.
Web Service WCF Web API Web services created as file with .asmx extension. WCF create with .svc extension Web API are simple class file with .cs(for C#) extension. Web API is inherited from “ApiController” and class name must end with “Controller”. It is SOAP based service and return data in XML form. It is also based on SOAP and return data in XML form. Web API is HTTP based service and by default it return data in JSON or XML form. It supports only HTTP protocol. It supports various protocols like TCP, HTTP, HTTPS, Named Pipes, and MSMQ. It supports HTTP protocol. It can be hosted only on IIS. It can be hosted with in the application or on IIS or using window service. It can be hosted with in the application or on IIS. It is not open source but can be consumed by any client that understands xml. It is not open source but can be consumed by any client t…

Calculate Sum and average of two or more Textbox values using JQuery

We can calculate sum and average of values entered in textboxes with the help of small piece of jQuery code.
First of all let’s create a HTML form where we’ll ask user to enter marks in each subject, under body section add following HTML:
<tableclass="demo-table"> <trclass="label"> <tdcolspan="2">Please enter marks(0-99):</td> </tr> <tr> <td>English</td> <td> <inputtype="text"class="txtMarks"name="txtMarks"