HttpClient冻结一些用户随机

时间:2015-07-24 11:08:14

标签: c# asp.net httpclient owin

我有一个接收URL和文件名的方法,然后该方法向该URL发出请求,下载HTML并将其转换为pdf。 问题是,有时发出请求的用户在client.GetStringAsync(URI_Target)完全冻结,如果发生这种情况,它将永远发生,而如果它起作用,它将始终有效(至少24小时)。

一个问题是目标网址需要身份验证,不同的用户可能会或者不能访问目标网页。

//HTTP get method
public async Task<ActionResult> Index(string URL, string FileName)
{
  //downloading the html from URl using the same Auth cookies for the current logged user
  string html = await GetHtmlAsync(new Uri(URL), Request.GetOwinContext().Request.Cookies);

  //... convert and return...
}


public static async Task<string> GetHtmlAsync(Uri URI_Target, RequestCookieCollection OwinCookieCollection)
    {
        var cookieContainer = new CookieContainer();
        using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer })
        using (var client = new HttpClient(handler))
        {
            if (OwinCookieCollection != null)
            {
                var rootUrl = new Uri(URI_Target.GetLeftPart(UriPartial.Authority));
                foreach (var cookie in OwinCookieCollection)
                {
                    cookieContainer.Add(new Cookie(cookie.Key, WebUtility.UrlEncode(cookie.Value)) { Domain = rootUrl.Host });

                }
            }

          //always reach this point, GetStringAsync sometimes takes forever (after a few seconds => System.Threading.Tasks.TaskCanceledException)
            var ris = await client.GetStringAsync(URI_Target).ConfigureAwait(false);
            //sometimes reach this point
            return ris;
        }
    }

0 个答案:

没有答案