How to consume Asp.Net Web API using C# ?

Introduction

Asp.Net web api can be consumed in different ways in asp .net web applications. Be it Javascript, jQuery or using C#.

This post will illustrate how to consume it via C# code.

Overview

ASP.NET Web API:  It is a framework which can easily build HTTP services can be accessible by clients, including browsers and mobile devices. Its an ideal platform for building RESTful applications on the .NET Framework.

Simple Code Snippet of Web API are given below.

public class ResponseType
{
public string Status { get; set; }
public string Token { get; set; }
}

[AllowAnonymous]
[HttpGet]
public HttpResponseMessage GetGlobalToken(string AutorizationKey)
{
try
{
HttpResponseMessage response = new HttpResponseMessage();
ResponseType objResponse = new ResponseType();
APIMethods objApiMethods = new APIMethods();

int intIsValidAuthKey = objApiMethods.IsValidAuthKey(AuthorizationKey);

//Validates the authorization key
if (intIsValidAuthKey == 1)
{
string strGlobalToken = ReturnToken();
objApiMethods.UpdateClientToken(dto.AuthorizationKey, strGlobalToken);

objResponse.Status = "Success";
objResponse.Token = strGlobalToken;
}

else
{
objResponse.Status = "Error";
objResponse.Token = "200";
}

response = Request.CreateResponse(HttpStatusCode.OK, objResponse, new MediaTypeHeaderValue(GetContentType));
return response;
}
catch (Exception ex)
{
throw ex;
}
}

In the above code, GetGlobalToken() is a web api method which gets Authorization Key as a parameter.
It matches the Authorization Key by passing it to database and if the key matches then it returns the response containing Status as well as Token.

Now we will consume this web api via C# code.
C# code snippet is given below.

private void DemoToConsumeApi()
{
string strAuthKey = string.Empty;

// Calls the web service by passing the parameters
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost/TestSite/DesktopModules/TestAPI/API/TestServices/");
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/xml"));

HttpResponseMessage response = client.GetAsync("GetGlobalToken?AuthorizationKey=" + strSignUpGlobalToken + "").Result;

// If response comes as success, then read the response
if (response.IsSuccessStatusCode)
{
var res = response.Content.ReadAsStringAsync().Result;

XDocument doc = XDocument.Parse(res);
XmlDocument xdoc = new XmlDocument();
doc.LoadXml(res);

XmlNodeList status = xdoc.GetElementsByTagName("Status");
XmlNodeList token = xdoc.GetElementsByTagName("Token");

strMessage = status[0].InnerText;
strToken = token[0].InnerText;

if(strMessage == "Success")
{
// Do operation
}
else
{
// See for error code in response
}
}

In the above method we are using the path of web api method as

http://localhost/TestSite/DesktopModules/TestAPI/API/TestServices/

because method is inside the DesktopModules of TestSite.

Conclusion

In this way we can easily consume the asp.net web api using C# code.

 

About these ads
About

Software Engineer | Mindfire Solutions, India

Tagged with: , , , , , , , , , ,
Posted in DotNetNuke
One comment on “How to consume Asp.Net Web API using C# ?
  1. […] How to consume Asp.Net Web API using C# ? (aspdotnetcms.wordpress.com) […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

Enter your email address to follow this blog and receive notifications of new posts by email.

Join 6 other followers

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: