Click here to Skip to main content
15,881,204 members
Articles / Web Development / HTML5
Tip/Trick

Implementing a Basic REST Based ASP.NET Web API Service with Multiple GET Methods and its Consumption using JQuery Client

Rate me:
Please Sign up or sign in to vote.
5.00/5 (15 votes)
22 Oct 2014CPOL4 min read 85.5K   1.5K   42   7
This tip guides through implementing a basic REST based Web API service with multiple GET methods and its consumption using JQuery client

Introduction

Web API is a set of APIs (Application Programming Interface) or framework for building REST based services on .NET platform to be consumed by desktop or mobile clients. ASP.NET Web API framework can be used to develop HTTP based services, here HTTP services means the services based on request-response between client and services.

Web API services are requested using HTTP Request methods like:

  • GET - Request data/resource
  • POST – Submit or create data/resource
  • PUT - Update data/resource
  • DELETE – Delete data/resource

Here in this tip, I will be walking through the basic steps involved in implementing the Web API services with multiple GET methods and its client consumption using JQuery. For demo purposes, we will develop a Calculator service exposing basic Addition/Subtraction/Division/Multiplication functionalities via HTTP GET methods and an HTML client consuming the services via JQuery AJAX call.

Note: This is only a sample intended to demonstrate multiple Web API GET methods in the same service class and its consumption using JQuery. For security reasons, web pages cannot make calls to services (APIs) on a domain other than the one where the page originated. Here in this demo article, I won’t be looking into Cross-origin resource sharing (CORS) - sharing /accessing resources between domains other than the originating one. There is CORS NuGet package available targeting Web API 2.0 or later. Please refer to the MSDN documentation for details on this. Also, I won’t concentrate on SQL injection and input validation as it’s a demo version.

I am using Visual Studio Express 2013 for Desktop as my development environment targeting .NET framework 4.5.

First, we will be creating our Math’s API Services project with multiple GET methods, and later a HTML page as client to consume the services.

Step 1

Create an ASP.NET Web Application as below:

Image 1

Step 2

Select Empty template and choose to add folders and core references for Web API.

Image 2

Now our solution explorer looks as below:

Image 3

Step 3

Next, we need to add the Math’s API controllers for our Web API services. Right click on Controller folder and add an Empty Web API controller template and name it MathController.cs as below:

Image 4

Select the Web API2 Controller template.

Image 5

Name the Controller as Math Controller.

Image 6

Step 4

Next add the below Web API services methods to the MathController.cs file.

C#
//MathController.cs file.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace WepAPI_Demo.Controllers
{
    public class MathController : ApiController
    {
        [HttpGet]
        public int Add(int value1, int value2)
        {
            return value1 + value2;
        }

        [HttpGet]
        public int Substract(int value1, int value2)
        {
            return value1 - value2;
        }

        [HttpGet]
        public int Multiply(int value1, int value2)
        {
            return value1 * value2;
        }

        [HttpGet]
        public int Divide(int value1, int value2)
        {
            return value1 / value2;
        }

        [HttpGet]
        public string Get()
        {
            return "default";
        }
    }
}

Just a brief on the above code, we have five HTTP GET methods, as the name says these methods just deliver basic mathematical operations.

Step 5

Since we have multiple GET methods, we need to add the necessary routing instructions under the App_Start/WebApiConfig.cs file. Add the below code in WebApiConfig.cs->Register() routine for multiple GET method support.

C#
<code>//App_Start folder -> WebApiConfig.cs
Using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace WebAPI_Demo
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            // Web API routes
            config.MapHttpAttributeRoutes();

           //For ApiController in ASP.NET  MVC to  support multiple GET methods ;
           //Add an additional routing before  default routing as follows

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

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

Now our Math Web API service is ready to be consumed.

Step 6

Next, we will create an HTML page as client and consume the API services. Here, I will be creating the client inside the API project itself. You are free to create a separate client project.

Under the solution explorer, create a folder and name as Web to hold the client HTML page.

Next, we need to add the jQuery library for calling our Web API services. Download JQuery library from http://jquery.com/download/ if you don’t have in your local system. Then add a folder named ‘web/scripts’ under the solution explorer and add the JQuery script file.

Optionally, you can load the JQuery script file from a content delivery network (CDN) server as a best practice. Just add the CDN path to the HTML client page.

Next add a HTML page under ‘Web’ folder and name it ‘client.html’. Now our solution explorer looks as below:

Image 7

Step 7

Add the below code to the client.html page.

HTML
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Caculator Client</title>
    <script src="scripts/jquery-1.10.2.js"></script>
    <script>
        $(document).ready(function () {

            $(":button").click(function () {
                var value1 = $("#txtValue1").val();
                var value2 = $("#txtValue2").val();
                var arg = "value1=" + value1 + "&value2=" + value2;
                var control = event.target || event.srcElement;
                var id = control.id

                //var urlString = "http://localhost:53460/api/math/";
                var urlString = "/api/math/";

                switch (id) {
                    case 'btnAdd':
                        urlString = urlString + "Add/?" + arg;
                        break;
                    case 'btnMinus':
                        urlString = urlString + "Substract/?" + arg;
                        break;
                    case 'btnMultiply':
                        urlString = urlString + "Multiply/?" + arg;
                        break;
                    case 'btnDivide':
                        urlString = urlString + "Divide/?" + arg;
                        break;
                    default:
                        urlString = urlString + "hello";

                }

                $.ajax({
                    url: urlString,
                    type: "GET",
                    dataType: 'json',
                    success: function (result) {
                        $("#txtResult").val(result);

                    },
                    error: function (xhr, status, error) {
                        var err = eval("(" + xhr.responseText + ")");
                        $("#txtResult").val(err.Message)
                    }
                });
            });

        });
    </script>

</head>
<body>
    <div style="text-align:center">
        <h2>Calculator client - JQuery</h2>

        <!-- Number type is not supported in IE9 and prior versions -->
        Please enter Value1 :   <input type="number"
        id="txtValue1" min="1" max="100"><br><br>
        Please enter Value2 :   <input type="number"
        id="txtValue2" min="1" max="100"><br /><br>
        Result from Math API Service : <input type="text"
        id="txtResult" disabled /><br /><br>
        <input type="button" value="Add" id="btnAdd">
        <input type="button" value="Substract" id="btnMinus">
        <input type="button" value="Multiply" id="btnMultiply">
        <input type="button" value="Divide" id="btnDivide">

    </div>

</body>
</html>

Now our client interface is ready to consume the web API services. Our client for Math Web API services looks as below. We have two input fields and buttons to invoke the API services. Once the buttons are clicked, using jQuery AJAX, we invoke the respective API call and output the result.

Image 8

To test the client, hit F5 (or whatever you have configured your debug key in Visual Studio) and our API services are ready to be consumed. Input some numeric values to the input text boxes. Then click on the respective button to invoke the API services. The output will be displayed in the output text area.

Note: Here in this demo version, Web API services and client page are in the same project. You can create a separate project for client and consume it. Just make sure to run the WEB API services before client consumption.

 

Please refer Part2 , which guides through implementing a basic REST based Web API service with multiple GET methods and its consumption using AngularJS client.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questionproblem about final result Pin
Member 1321057123-May-17 2:27
Member 1321057123-May-17 2:27 
QuestionWhats going on with var control? Pin
Brian Bollig2-Dec-15 9:20
Brian Bollig2-Dec-15 9:20 
Bug"event" unknown in line 13 of the html file Pin
BeeWayDev23-Oct-14 9:10
BeeWayDev23-Oct-14 9:10 
GeneralRe: "event" unknown in line 13 of the html file Pin
Mathew Soji23-Oct-14 16:58
professionalMathew Soji23-Oct-14 16:58 
Ok, Thank You.
Soji Mathew

GeneralRe: "event" unknown in line 13 of the html file Pin
Mathew Soji28-Oct-14 4:04
professionalMathew Soji28-Oct-14 4:04 
GeneralRe: "event" unknown in line 13 of the html file Pin
BeeWayDev28-Oct-14 6:40
BeeWayDev28-Oct-14 6:40 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun22-Oct-14 20:12
Humayun Kabir Mamun22-Oct-14 20:12 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.