conter12

In this article we will see how to consume a simple Web API that we have hosted on local IIS in our Windows Application.

Consuming a Simple Web API in windows client:

Now I will just create File -> New -> Project and I am going to create a Windows Forms Application and I will browse it to folder. I will name it as WindowsClient.

I am going to create a very simple project. Here I will have a button and a label. On the button click I am going to consume the API that we have hosted on IIS in our previous article

Now to consume this API, I need a class called as HttpClient. So I am going to work with HttpClient. This HttpClient is present in a namespace that is nothing but System.Net.Http (We need to add a reference). And this HttpClient class resides in System.Net.Http namespace

var client = new HttpClient();

Next step is to create a base address. As I told you Web APIs works on a base URI. My base address is http://thinkpad-pc/MyFirstAPI/

var client = new HttpClient();

client.BaseAddress = new Uri("http://thinkpad-pc/MyFirstAPI/");

Next I need to call the particular API method. For calling that API method I am using client.GetAsync method. So basically we have Asynchronous method which works with await and async keywords. If you are not aware of await and async programming, it is very simple you can just have a look in my free C# course. It is very simple whenever you are using await your method should have async.

client.GetAsync("api/MTT") will get me the response. I am going to read that response in a string using response.Content.ReadAsStringAsync() method and store it into the result. And result will be finally displayed it in the label. Below code demonstrate the same

using System;
using System.Net.Http;
using System.Windows.Forms;

namespace WindowsClient
{

public partial class Form1 : Form
{

public Form1()
{
InitializeComponent();
}
private async void button1_Click(object sender, EventArgs e)
{
var client = new HttpClient();
client.BaseAddress = new Uri("http://thinkpad-pc/MyFirstAPI/");
HttpResponseMessage response = await client.GetAsync("api/MTT");
string result = await response.Content.ReadAsStringAsync();
label1.Text = result;
}

}

}

That’s it. I will execute this.

Click the button. You get both the strings. You see that the return type is of JSON. By default it works on JSON. What is JSON? And what is that return type? We will see that in our future articles.

Instead of api/MTT I can also go for /api/MTT/1

HttpResponseMessage response = await client.GetAsync("api/MTT/1");

I should get asp.

So that’s it. This is how you can consume Web API in your Windows Application or even in your Web Application through C#. C# server side code has the facility to use HttpClient and HttpResponseMessage. Now we will see how to consume Web API in Web Application using jQuery.

Consuming a Simple Web API in Web Application using jQuery:

I will just go for File à New à Project and I am going to create ASP.NET Web Application. I will name it as WebClient. I will select Empty Web Forms application. I will click OK.

Now Right click on project add a WebForm. I will name it as GetData.

So this time I am going to use jQuery and of course I can go to the code behind and I can implement using HttpClient class as we have seen in Windows Application. But this time I want to show you how to implement with jQuery based AJAX call.

So first of all I need add jQuery from NuGet.

Then I need to install AJAX i.e., Microsoft jQuery Unobtrusive Ajax.


Drag and drop these scripts from scripts folder to head section to GetData.aspx page. Now we are ready with jQuery and AJAX call.

<script src="Scripts/jquery-2.1.4.min.js"></script>
<script src="Scripts/jquery.unobtrusive-ajax.min.js"></script>

Say I have a button. Now I want to get data from the Web API on this button click

So I need to go for writing my script in separate script tag. On document ready then on button click (id is btnGetData). I want to make jQuery based AJAX call which is shown below. You can see that in $.ajax the type request is GET and url is the complete URI (my Web API location).

<input type="button" id="btnGetData" value="GetData" />

<script type="text/javascript">

$(document).ready(function () {

$("#btnGetData").click(function () {

$.ajax({

type: "GET",

url: "http://thinkpad-pc/MyFirstAPI/api/MTT",

success: function (data) { // ‘data’ will have all the result data from API

console.log(data); // If it is successful

},

error: function () {

console.log('Error in Reading'); //If it fails

}

});

});

});

</script>

Now, Let me execute, press F5. On browser press F12 to see our log in the console.

Now, I will click on GetData.

Now click on console tab, You see an error saying that No ‘Access-Control-Allow-Origin’.

This is basically an error because we have hosted our API at this URL (http://thinkpad-pc/MyFirstAPI/api/MTT) or the domain specified and we are trying to access it on localhost:4695 which is a different domain. It is a kind of cross domain access.

So to enable this we need to go for CORS. You might have heard about CORS. Google CORS in Web API. It will get lot of things. Anyway in our future articles we are going to learn about this.

So as of now I will go to my Web API project and install CORS DLLs from Nuget. Search for Cors and install Microsoft.AspNet.WebApi.Cors. I have already installed from Manage NuGet packages. It contains Cross-Origin Resource Sharing.


You can see the DLLs.

Once I install CORS. There are two steps that I need to perform. First of all I need to go to WebApiConfig.cs file in App_Start folder and I need to add config.EnableCors

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web.Http;

using System.Web.Http.Cors;

namespace MyFirstWebAPI

{

public static class WebApiConfig

{

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}/{id}",

defaults: new { id = RouteParameter.Optional }

);

}

}

}

You can see this EnableCors is present in System.Web.Http.Cors. Even it is present in System.Web.Http we need Cors.

Second step is to go to the controller where I want to enable this cross domain sharing. I need to simple add an attribute EnableCors for any type of request. And rebuild the web api project.

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 MyFirstWebAPI.Controllers

{

[EnableCors("*","*","*")]

public class MTTController : ApiController

{

private string[] S = new

string[] { "ManzoorTheTrainer", "asp" };

// ../api/MTT

public string[] Get()

{

return S;

}

// ../api/MTT/id

public string Get(int id)

{

return S[id];

}

}

}

This is my client which is already running. Refresh the page and let me click GetData. You see that it is writing in the console. It is working fine. So this is how you enable cross domain sharing on Controller level.

Now if I want to enable it on the complete project level, I need not to put [EnableCors("*","*","*")] on each Controller. I can simply go to WebApiConfig. I can add policy. We call it as a policy. So here I am going to create an object of EnableCorsAttribute which is available in the class System.Web.Http.Cors and while enabling Cors I am passing that attribute object. This will enable Cross Domain Sharing at the complete application level or your complete service level. Let me rebuild this. I have already hosted it. Whenever I rebuild it is going to take the latest version in the host.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web.Http;

using System.Web.Http.Cors;

namespace MyFirstWebAPI

{

public static class WebApiConfig

{

public static void Register(HttpConfiguration config)

{

// Web API configuration and services

var corsAttr = new EnableCorsAttribute("*", "*", "*");

config.EnableCors(corsAttr);

//config.EnableCors();

// Web API routes

config.MapHttpAttributeRoutes();

config.Routes.MapHttpRoute(

name: "DefaultApi",

routeTemplate: "api/{controller}/{id}",

defaults: new { id = RouteParameter.Optional }

);

}

}

}

My client is still running. Refresh and click on GetData. It should work as expected. So I am getting both the things.

If I want a particular record, I will definitely say 1 Save All. Refresh and click GetData. I get asp, that’s it. This is how you can consume Web API in your Web Applications using AJAX and jQuery based calls.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="GetData.aspx.cs" Inherits="WebClient.GetData" %>

<!DOCTYPE html>

<head runat="server">

<title></title>

<script src="Scripts/jquery-2.1.4.min.js"></script>

<script src="Scripts/jquery.unobtrusive-ajax.min.js"></script>

<script type="text/javascript">

$(document).ready(function () {

$("#btnGetData").click(function () {

$.ajax({

type: "GET",

url: "http://thinkpad-pc/MyFirstAPI/api/MTT/1",

success: function (data) {

console.log(data);

},

error: function () {

console.log('Error in Reading');

}

});

});

});

</script>

</head>

<body>

<form id="form1" runat="server">

<div>

<input type="button" id="btnGetData" value="GetData" />

</div>

</form>

</body>


Next article coming soon.. :)