我试图向WebAPI控制器发出HTTP POST请求,我从我的服务中调用它。这是我要注入我的业务层以便进行调用的类:
/// <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
}
}
}
}
我意识到它的运行速度非常慢,每次请求大约需要30秒。
作为一项实验,我尝试使用以下代码从Chrome控制台执行请求,并且快速运行 - 眨眼之间:
$.post("http://localhost:8080/Api/FinishedTakersCount", { "QuizOwnerUserId": 1, UrlId: "0mFjBH" }, null);
我还创建了一个快速控制台应用程序来测试功能,这也在眨眼之间运行:
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);
}
}
}
}
您可以在上面的代码中看到我发布的值。
我不能理解为什么会花这么长时间,因为我在Window Service中运行请求。
在本地计算机上安装时是否进行调用,或者在Visual Studio中调试它是否相同 - 单步执行client.UploadValues(...)需要30秒左右的时间结果很好。
为什么我的Windows服务(在VS中安装或调试)运行缓慢,但每次执行AJAX请求或从控制台应用程序请求时都会快速闪烁?