HttpClient调用保持等待模式,但在Console App中运行良好

时间:2018-12-04 20:46:00

标签: c# asp.net-web-api dotnet-httpclient httpresponsemessage

下面是当我在控制台应用程序上执行代码时工作得很好的代码。 线
var postResponse =等待客户端。SendAsync(req); 在控制台应用程序中运行代码时给出结果。

但是当iam在WebApi控制器中使用此代码时,该代码将在此行中停止。

 using (var client = new HttpClient())
        {


            var auth = "MTAwNDgucnVsZXNlbmdpbmUuc2VydmljZTp2N3FuY3I4cWlz";
            client.BaseAddress = new Uri("https://federation-sts-stage.accenture.com");
            var req = new HttpRequestMessage(HttpMethod.Post, "https://federation-sts-stage.test.com/oauth/ls/connect/token");
            var cont = new FormUrlEncodedContent(bodyContents);
            cont.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            cont.Headers.ContentLength = Convert.ToInt64("125");
            req.Content = cont;
            req.Headers.Add("Authorization", "Basic " + auth);


            try
            {
                var postResponse = await client.SendAsync(req); // this is where the code keeps on waiting but works fine in console app
                postResponse.EnsureSuccessStatusCode();
                responseContents = postResponse.Content.ReadAsStringAsync().Result;


            }
            catch (Exception ex)
            {
                var msg = ex.Message;
                return msg;
            }


            var responseObject = JObject.Parse(responseContents);
            return responseObject.Value<string>("access_token");
        }

在两种情况下(在控制台应用程序和webapi控制器调用中),我也都比较了请求对象,但是在两种情况下,请求对象都与以下内容相同:

{Method: POST, RequestUri: 'https://federation-sts-stage.test.com/oauth/ls/connect/token', Version: 1.1, Content: System.Net.Http.FormUrlEncodedContent, Headers:
{
  Authorization: Basic MTAwNDgucnVsZXNlbmdpbmUuc2VydmljZTp2N3FuY3I4cWlz
  Content-Type: application/json
  Content-Length: 125
}}

我不知道我在做什么错。

根据评论,我将整个方法从apicontroller调用,如下所示,该方法在控制台应用程序中工作正常,但是当我从apicontroller调用此方法时,该方法将继续运行。

public async Task<string> RequestTokenFromIssuer(string username, string password)
    {

        var bodyContents = new Dictionary<string, string>
        {
            { "grant_type", "client_credentials" },
            { "userName", username },
            { "password", password},
            { "scope", "read_rulesengine write_rulesengine" }
        };

        string responseContents = string.Empty;

        using (var client = new HttpClient())
        {


            var auth = "MTAwNDgucnVsZXNlbmdpbmUuc2VydmljZTp2N3FuY3I4cWlz";
            client.BaseAddress = new Uri("https://federation-sts-stage.test.com");
            var req = new HttpRequestMessage(HttpMethod.Post, "https://federation-sts-stage.test.com/oauth/ls/connect/token");
            var cont = new FormUrlEncodedContent(bodyContents);
            cont.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            cont.Headers.ContentLength = Convert.ToInt64("125");
            req.Content = cont;
            req.Headers.Add("Authorization", "Basic " + auth);


            try
            {
                var postResponse = await client.SendAsync(req);
                postResponse.EnsureSuccessStatusCode();
                responseContents = postResponse.Content.ReadAsStringAsync().Result;


            }
            catch (Exception ex)
            {
                var msg = ex.Message;
                return msg;
            }


            var responseObject = JObject.Parse(responseContents);
            return responseObject.Value<string>("access_token");
        }

    }

1 个答案:

答案 0 :(得分:2)

我相信您的问题实际上就在网上

responseContents = postResponse.Content.ReadAsStringAsync().Result;

永远不要在异步方法中做到这一点。您应该这样做:

responseContents = await postResponse.Content.ReadAsStringAsync();