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:
Step 2
Select Empty template and choose to add folders and core references for Web API.
Now our solution explorer looks as below:
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:
Select the Web API2 Controller template.
Name the Controller as Math Controller.
Step 4
Next add the below Web API services methods to the 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.
<code>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)
{
config.MapHttpAttributeRoutes();
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:
Step 7
Add the below code to the client.html page.
<!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 urlString = urlString + "Add/?" + arg;
break;
case urlString = urlString + "Substract/?" + arg;
break;
case urlString = urlString + "Multiply/?" + arg;
break;
case urlString = urlString + "Divide/?" + arg;
break;
default:
urlString = urlString + "hello";
}
$.ajax({
url: urlString,
type: "GET",
dataType: 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>
-->
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.
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.