使用system.threading.tasks.task.throwifexceptional exception调用HttpClient.PostAsync()取消任务

时间:2015-11-12 12:27:55

标签: .net multithreading cross-domain httpclient

我正在尝试从HTML创建PDF。这部分是在带有第三方工具的PHP文件中完成的。在开发服务器上测试时工作正常。但是,当移动到实时服务器时,对 HttpClient.PostAsync 的调用低于错误。

  

at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean   includeTaskCanceledExceptions)at   System.Threading.Tasks.Task' 1.GetResultCore(布尔   waitCompletionNotification)at   System.Threading.Tasks.Task' 1.get_Result()   at myProject.mymethod(Int32 [] myIds)in path \ MyClass.cs:line

我的代码:

public static void TestFunction()
{
    try
    {
        string htmlToRender = "My Test Data";

        // Convert the string into HttpContent object
        HttpContent stringContent = new StringContent(htmlToRender);

        using (var formData = new MultipartFormDataContent())
        {
            formData.Add(stringContent, "htmlToRender");

            Task<System.IO.Stream> response = GetHttpContent(formData);

            return response.Result;
        }
    }
    catch (HttpRequestException ex)
    {
        Console.WriteLine(ex.Message + "innerExc" + ex.InnerException);
        Console.ReadLine();
    }
}

private async Task<Stream> GetHttpContent(MultipartFormDataContent ahttpContent)
{
    using (var client = new HttpClient())
    {

        HttpResponseMessage response = await client.PostAsync(
                        "--My request uri to the PHP file--", ahttpContent);

        if (!response.IsSuccessStatusCode)
        {
            return null;
        }
        return response.Content.ReadAsStreamAsync().Result;
    }
}

.Net框架版本升级到4.5

0 个答案:

没有答案