Saturday, 17 March 2018

Call (Consume) Web API using jQuery

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 FileNewProject. 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 .

Creating asp.net web api application

Now new window will open as shown below.
Now Select Empty Template, check on Web API checkbox and click on OK.

Selecting asp.net web api empty template

Now, a new project will be created as shown below.

Asp.net web api empty folder structure

Modify Web API Routing

Open WebApiConfig.cs file. Visual studio generates default routing as shown below. Add {action} in routeTemplate as highlighted in yellow.

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

namespace WebApiDemo
{
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}
}

Adding API Controller

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
{
    public class HomeController : ApiController
    {
        // Method 1- Using premitive data types with GET attribute
        [HttpGet]
        public string Calculate1(int FirstNumber, int SecondNumber)
        {
            return "Addition is: " + (FirstNumber + SecondNumber).ToString();
        }

        // Method 2- Using Complex data type with POST attribute
        [HttpPost]
        public string Calculate2(Calculator obj)
        {
            return "Addition is: " + (obj.FirstNumber + obj.SecondNumber).ToString();
        }
    }

    public class Calculator
    {
        public int FirstNumber { get; set; }
        public int 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.

protected void Application_BeginRequest()
{
    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
    if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
    {
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
        HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
        HttpContext.Current.Response.End();
    }
}
Enabling CORS in Web API 2.0 →

You can enable CORS in Web API 2.0 using nuget package manager.

Step 1: Installing CORS

Go to TOOLS → Nuget Package Manager → Package Manager Console → Type below command and press enter.
PM> Install-Package Microsoft.AspNet.WebApi.Cors

Step 2: Register CORS

Register CORS in Register method as shown below.

public static void Register(HttpConfiguration config)
{
    // Web API configuration and services
    config.EnableCors();
    // Web API routes
    config.MapHttpAttributeRoutes();

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{action}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
}
Step 3: Enable CORS

We can enable CORS at contoller level, action or global level as shown below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;

namespace WebApiDemo.Controllers
{
    [EnableCors(origins: "http://localhost:50597", headers: "*", methods: "*")]
    public class HomeController : ApiController
    {
        // Method 1- Using premitive data types with GET attribute
        [HttpGet]
        public string Calculate1(int FirstNumber, int SecondNumber)
        {
            return "Addition is: " + (FirstNumber + SecondNumber).ToString();
        }

        // Method 2- Using Complex data type with POST attribute
        [HttpPost]
        public string Calculate2(Calculator obj)
        {
            return "Addition is: " + (obj.FirstNumber + obj.SecondNumber).ToString();
        }
    }

    public class Calculator
    {
        public int FirstNumber { get; set; }
        public int 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.

WebForm1.aspx code
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {

        $('#btn1').click(function () {
            $('#Result').html('');
            var FirstNumber = $('#txtFirstNumber').val();
            var SecondNumber = $('#txtSecondNumber').val();
            $.ajax({
                type: 'GET',
                url: 'http://localhost:29279/api/home/calculate1?FirstNumber=' + FirstNumber + '&SecondNumber=' + SecondNumber + '',
                dataType: 'json',
                success: function (data) {
                    $('#Result').append(data);
                }
            });
        });

        $('#btn2').click(function () {
            $('#Result').html('');
            var input = { FirstNumber: $('#txtFirstNumber').val(), SecondNumber: $('#txtSecondNumber').val() };
            $.ajax({
                type: "POST",
                url: 'http://localhost:29279/api/home/calculate2',
                data: JSON.stringify(input),
                dataType: "json",
                context: document.body,
                contentType: 'application/json', //contentType: "application/json;charset=utf-8",
                success: function (d) {
                    $('#Result').append(d);
                }
            });
        });

    });
</script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <input type="text" id="txtFirstNumber" />
            <input type="text" id="txtSecondNumber" />
            <input type="button" id="btn1" value="Call Calculate 1" />
            <input type="button" id="btn2" value="Call Calculate 2" />
            <br />
            <label id="Result" style="color:green;"></label>
        </div>
    </form>
</body>
</html>

Now run asp.net webform application, output should be look like this.

Call web api using jquery

Now put some number in both textbox and click on Call Calculate1 button. You will see addition of both entered numbers.

Call web api using jquery with http get method

Now put some number in both textbox and click on Call Calculate2 button. You will see addition of both entered numbers.

Call web api using jquery with http post method
Share:

0 comments:

Post a Comment

Email Subscription

Subscribe to our newsletter to get the latest articles directly into your inbox

Blog Archive

BUY FROM AMAZON