In this tutorial, I am going to explain you how to create simple asp.net web api application and consume web api using jQuery. We will be using Visual Studio 2013.
Creating Web API Empty Application
First step is to create ASP.NET Web API empty application as shown below.
Go to File → New → Project. A new window will be open as shown below.
Now go to Web and select .NET Framework 4.5 and give project name and click on OK .
Now new window will open as shown below.
Now Select Empty Template, check on Web API checkbox and click on OK.
Now, a new project will be created as shown below.
Modify Web API Routing
Open WebApiConfig.cs file. Visual studio generates default routing as shown below. Add {action} in routeTemplate as highlighted in yellow.
Next step is to add api controller to application. Go to Controller folder → Add → Controller.. → select 'Web API 2 Controller-Empty'. Give its name HomeController and click on Add. In home controller class, we have two method which perform addition of two numbers and returns string. Calculate1 method takes two premitive parameter through url using HttpGet verb and Calculate2 method takes one complex data through body using HttpPost verb.
using System;
using
System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace
WebApiDemo.Controllers
{
publicclassHomeController : ApiController
{
// Method 1- Using premitive data types with GET attribute
[HttpGet]
publicstring Calculate1(int FirstNumber, int SecondNumber)
{
return"Addition is: "
+ (FirstNumber + SecondNumber).ToString();
}
// Method 2- Using Complex data type with POST attribute
[HttpPost]
publicstring Calculate2(Calculator obj)
{
return"Addition is: "
+ (obj.FirstNumber + obj.SecondNumber).ToString();
}
}
publicclassCalculator
{
publicint FirstNumber { get; set; }
publicint SecondNumber { get; set; }
}
}
Modify Global.asax.cs File
Enabling CORS in Web API 1.0 →
If you are using Web API 1.0 then you need to modify global.asax file to enable cors for ajax request to work. Add below code Application_BeginRequest event.
// Method 1- Using premitive data types with GET attribute
[HttpGet]
publicstring Calculate1(int FirstNumber, int SecondNumber)
{
return"Addition is: "
+ (FirstNumber + SecondNumber).ToString();
}
// Method 2- Using Complex data type with POST attribute
[HttpPost]
publicstring Calculate2(Calculator obj)
{
return"Addition is: "
+ (obj.FirstNumber + obj.SecondNumber).ToString();
}
}
publicclassCalculator
{
publicint FirstNumber { get; set; }
publicint SecondNumber { get; set; }
}
}
Call Web API Using jQuery
Create an asp.net webform application and add new webform to it and write below code to call web api. Here we have jquery reference file to make jQuery works, two html textbox to for two numbers and two buttons to call Calculate1 and Calculate2 methods.