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.

This folder contains application data files.
Contains different configuration files
All the themes and styles files are added under this folder.
Conations Web API controllers
Contains Images of the project
Models folder used to create Model under it, by default there is no Model.
All the client script files located under this folder.
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 = "", City = "Gurgaon" },
            new Customer {Id=2, Name = "Customer1", Email = "", City = "Gurgaon" },
            new Customer {Id=3, Name = "Customer2", Email = "", City = "Gurgaon" },
            new Customer {Id=4, Name = "Customer3", Email = "", City = "Gurgaon" },
            new Customer {Id=5, Name = "Customer4", Email = "", 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

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

Read and parse a CSV file into an array of rows and columns in C#

The following PopulateCsvIntoArraymethod used to read the CSV file into a two-dimensional array of strings.
I have included explanation of method lines, wherever needed. ///<summary> /// Populate the CSV file into an array, /// We assume that every line has the same number of fields and there may be blank lines. ///</summary> ///<returns></returns> privatestring[,] PopulateCsvIntoArray() { // Get path of CSV file. var path = Server.MapPath("~/Folder_Name/testfile.csv"); // Get the file's text using ReadAllText method. string fileData = System.IO.File.ReadAllText(path);
// Split CSV data into lines.     fileData = fileData.Replace('\n', '\r'); string[] lines = fileData.Split(newchar[] { '\r' }, StringSplitOptions.RemoveEmptyEntries);
// Get rows and columns counts. int totalRows = lines.Length;

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"