I'm trying to make a HTTP POST request to a WebAPI Controller, I am calling it from my service. Here is the class that I am injecting into my business layer in order to make the calls:
/// <summary>
/// Makes calls to WebAPI
/// </summary>
public class WebApiProxy : IWebApiProxy
{
/// <summary>
/// Sends HTTP POST requests to WebAPI along with post values
/// </summary>
/// <param name="apiControllerName">The name of the controller to call</param>
/// <param name="postValues">The values to post to the controller</param>
public void SendApiRequest(string apiControllerName, NameValueCollection postValues)
{
using (var client = new WebClient())
{
try
{
//
// Breakpoint below this line, it's where it hangs
//
byte[] responsebytes = client.UploadValues(string.Format("http://localhost:8080/Api/{0}", apiControllerName), "POST", postValues);
string responsebody = Encoding.UTF8.GetString(responsebytes);
}
catch (Exception)
{
// TODO: Handle failed requests
}
}
}
}
I realised that it is running extremely slowly, probably around 30 seconds for every request.
As an experiment I tried doing the request from the console in Chrome using the following code and it runs lightening fast - in the blink of an eye:
$.post("http://localhost:8080/Api/FinishedTakersCount", { "QuizOwnerUserId": 1, UrlId: "0mFjBH" }, null);
I also created a quick console app to test the functionality and this also runs in the blink of an eye:
static void Main(string[] args)
{
while(true)
{
Console.WriteLine("Press Enter to make web request, or type exit...");
var typed = Console.ReadLine();
if (typed == "exit")
{
break;
}
using (var client = new WebClient())
{
try
{
var apiControllerName = "LiveTakersCount";
var postValues = new NameValueCollection();
postValues.Add("QuizOwnerUserId", "1");
postValues.Add("UrlId", "0mFjBH");
//TODO: Remove port from localhost
byte[] responsebytes = client.UploadValues(string.Format("http://localhost:8080/Api/{0}", apiControllerName), "POST", postValues);
string responsebody = Encoding.UTF8.GetString(responsebytes);
Console.WriteLine("HTTP Request completed.");
}
catch (Exception ex)
{
// TODO: Handle failed requests
Console.WriteLine("An Exception occurred with the web request: {0}", ex.Message);
}
}
}
}
You can see the values that I am posting in the above code.
I can't for the life of me understand why it would be taking so long, just because I am running the request within a Window Service.
It is the same whether it makes the call when installed on my local machine or if I debug it within Visual Studio - stepping over client.UploadValues(...) takes 30 seconds or so and the result is fine.
Why is it running slow in my Windows Service (installed or debugging in VS), but lightening fast every time when doing an AJAX request or request from a console application?