HttpClient.SendAsync方法退出而不抛出异常

时间:2016-11-08 06:22:18

标签: c# asynchronous async-await httpclient

我正在调用以下函数来获取访问令牌,以便使用REST Api检索Twitter用户配置文件。

  public async Task<string> GetAccessToken()
    {
        try
        {
            var httpClient = new HttpClient();
            var request = new HttpRequestMessage(HttpMethod.Post, "https://api.twitter.com/oauth2/token ");
            var customerInfo = Convert.ToBase64String(new UTF8Encoding().GetBytes(OAuthConsumerKey + ":" + OAuthConsumerSecret));
            request.Headers.Add("Authorization", "Basic " + customerInfo);
            request.Content = new StringContent("grant_type=client_credentials", Encoding.UTF8, "application/x-www-form-urlencoded");

            //program exits at this point 
            HttpResponseMessage response = await httpClient.SendAsync(request).ConfigureAwait(false);
            string json = await response.Content.ReadAsStringAsync();
            var serializer = new JavaScriptSerializer();
            dynamic item = serializer.Deserialize<object>(json);
            return item["access_token"];
        }
        catch (Exception ex)
        {
            MessageBox.Show("In  Retrieving access token : " + ex.ToString());
        }

    }

程序退出/终止而不会在HttpResponseMessage response = await httpClient.SendAsync(request).ConfigureAwait(false);点检索响应。

这是调用 GetAccessToken()

的父函数
public async Task getUserProfile(string userName)
    {
        try
        {
            if (accessToken == null)
            {
                accessToken = await GetAccessToken().ConfigureAwait(false);
            }

            var request = new HttpRequestMessage(HttpMethod.Get, string.Format(" https://api.twitter.com/1.1/users/show.json?screen_name={0}", userName));
            request.Headers.Add("Authorization", "Bearer " + accessToken);
            var httpClient = new HttpClient();
            HttpResponseMessage response = await httpClient.SendAsync(request).ConfigureAwait(false);
            var jsonString = await response.Content.ReadAsStringAsync();

            var serializer = new JavaScriptSerializer();
            dynamic jsonObj = serializer.Deserialize<object>(jsonString);

        }

        catch (Exception ex)
        {
            if (DEBUG)
            {
                MessageBox.Show("In  Retrieving user profile from twitter : " + ex.ToString());
            }

        }

    }

我无法捕获到为什么程序退出GetAccessToken()或getUserProfile()的异常。但是,如果getUserProfile()具有Task<IEnumerable<string>>作为返回类型,则代码会成功执行并检索HttpResponseMessage。为什么会出现这个问题?如何捕获异常?

2 个答案:

答案 0 :(得分:2)

您的应用程序过早退出,因为您没有等待getUserProfile()完成。您可以将getTwitterInfo标记为与其他人类似的异步,或者告诉它等待任务完成

public async Task getTwitterInfo() { 
    var twitter = new Twitter("consumerKey","consumerSecret");
    await twitter.getUserProfile(userName); 
}

OR

public void getTwitterInfo() { 
    var twitter = new Twitter("consumerKey","consumerSecret");
    var task = twitter.getUserProfile(userName); 
    var result = task.WaitAndUnwrapException();
}

答案 1 :(得分:-2)

你试过吗

    HttpResponseMessage response = httpClient.SendAsync(request).Result;

我在自己的代码中遇到了同样的问题,这似乎修复了它,应该等同于原始调用。不过,我仍然不了解坠机的根本原因。