Hi,
I am trying to call or consume WebAPI through client application (Windows forms) for asynchronous calling via HTTP client. It should return a response as the no of requests for WebAPI along with time interval......
There is no exceptions in the program.These red lines are of format basis. Below is my code I had tried can u please check the code and send back my the solution.These is of high priority.Hope some one responds early
Source Code:
using System;using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace semVoip_TestTool
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btn_Start_Click(object sender, EventArgs e)
{
// Thread AutoUserRegistrationThread = new Thread(AutoUserRegistrationASync);
//AutoUserRegistrationThread.CurrentCulture = CultureInfo.InvariantCulture;
//AutoUserRegistrationThread.Name = "AutoUserRegistrationThread";
//AutoUserRegistrationThread.Start();
//btn_Start.IsAccessible = true;
Console.WriteLine();
RunASync().Wait();
}
public static async Task RunASync()
{
// Console.WriteLine("Calling the back-end API");
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://107.108.32.145/semVoIP");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// //string apiBaseAddress ="http://107.108.32.145/WebApiHMACAuthentication/";
string apiBaseAddress = "http://107.108.32.145/semVoIP/";
CustomDelegatingHandler customDelegatingHandler = new CustomDelegatingHandler();
//HttpClient client = HttpClientFactory.Create(customDelegatingHandler);
//HttpResponseMessage response = await client.PostAsJsonAsync(apiBaseAddress + "API/GetUserDetails");
HttpResponseMessage response = await client.GetAsync(apiBaseAddress + "API/GetUserDetails");
if (response.IsSuccessStatusCode)
{
string responseString = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseString);
Console.WriteLine("HTTP Status: {0}, Reason {1}. Press ENTER to exit", response.StatusCode, response.ReasonPhrase);
Console.WriteLine();
}
else
{
Console.WriteLine("Failed to call the API. HTTP Status: {0}, Reason {1}", response.StatusCode, response.ReasonPhrase);
}
//using (var client = new HttpClient())
//{
// client.BaseAddress = new Uri("http://107.108.32.145/semVoIP/");
//client.DefaultRequestHeaders.Accept.Clear();
//client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// New code:
//HttpResponseMessage response = await client.GetAsync("api/GetUserDetails");
//if (response.IsSuccessStatusCode)
//{
//}
}
}
public class CustomDelegatingHandler : DelegatingHandler
{
//Obtained from the server earlier, APIKey MUST be stored securly and in App.Config
private string APPId = "4d53bce03ec34c0a911182d4c228ee6c";
private string APIKey = "A93reRTUJHsCuQSHR+L3GxqOJyDmQpCgps102ciuabc=";
protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
HttpResponseMessage response = null;
string requestContentBase64String = string.Empty;
string requestUri = System.Web.HttpUtility.UrlEncode(request.RequestUri.AbsoluteUri.ToLower());
string requestHttpMethod = request.Method.Method;
//Calculate UNIX time
DateTime epochStart = new DateTime(1970, 01, 01, 0, 0, 0, 0, DateTimeKind.Utc);
TimeSpan timeSpan = DateTime.UtcNow - epochStart;
string requestTimeStamp = Convert.ToUInt64(timeSpan.TotalSeconds).ToString();
//create random nonce for each request
string nonce = Guid.NewGuid().ToString("N");
//Checking if the request contains body, usually will be null wiht HTTP GET and DELETE
if (request.Content != null)
{
byte[] content = await request.Content.ReadAsByteArrayAsync();
MD5 md5 = MD5.Create();
//Hashing the request body, any change in request body will result in different hash, we'll incure message integrity
byte[] requestContentHash = md5.ComputeHash(content);
requestContentBase64String = Convert.ToBase64String(requestContentHash);
}
//Creating the raw signature string
//string signatureRawData = String.Format("{0}{1}{2}{3}{4}{5}", APPId, requestHttpMethod, requestUri, requestTimeStamp, nonce, requestContentBase64String);
string signatureRawData = "SEMVOIP";
var secretKeyByteArray = Convert.FromBase64String(APIKey);
byte[] signature = Encoding.UTF8.GetBytes(signatureRawData);
using (HMACSHA256 hmac = new HMACSHA256(secretKeyByteArray))
{
byte[] signatureBytes = hmac.ComputeHash(signature);
string requestSignatureBase64String = Convert.ToBase64String(signatureBytes);
//Setting the values in the Authorization header using custom scheme (amx)
// request.Headers.Authorization = new AuthenticationHeaderValue("amx", string.Format("{0}:{1}:{2}:{3}", APPId, requestSignatureBase64String, nonce, requestTimeStamp));
request.Headers.Authorization = new AuthenticationHeaderValue("amx", APPId + ":" + requestSignatureBase64String + ":9768b26d0560483bafb6d58afe6fa1b3:1469014188");
}
response = await base.SendAsync(request, cancellationToken);
return response;
}
}
}
}