简体   繁体   English

ASP.NET任务异步WaitingForActivation

[英]ASP.NET Task Async WaitingForActivation

I am trying to send a post request to a third party API and retrieve the UserToken. 我正在尝试将发布请求发送到第三方API并检索UserToken。 Here is the code that does that: 这是执行此操作的代码:

        [HttpPost]
        private async Task<string> GetUserToken()
        {
            using (var client = new HttpClient())
            {
                var parameters = new Dictionary<string, string>
                {
                    {"grant_type", "client_credentials" },
                    {"client_id", _clientId },
                    {"client_secret", _clientSecret }
                };
                var content = new FormUrlEncodedContent(parameters);

                var response = await client.PostAsync(_baseUrl, content);
                var responseString = await response.Content.ReadAsStringAsync();
                Console.WriteLine(responseString);
                UserTokenModel userToken = JsonConvert.DeserializeObject<UserTokenModel>(responseString);
                Console.WriteLine(userToken.access_token);
                return userToken.access_token;
            }
        }

When I test this in a console application, it prints out the correct UserToken value. 当我在控制台应用程序中对此进行测试时,它会打印出正确的UserToken值。 However, when I do a method call to this method and step through it in the debugger, the value of the Usertoken is set 但是,当我对该方法进行方法调用并在调试器中逐步调试它时,将设置Usertoken的值

var userToken = GetUserToken(); Status: WaitingForActivation Method:"{null}" Result:"{Not yet Computed}" Status: WaitingForActivation Method:"{null}" Result:"{Not yet Computed}"

I'm not really sure why this is happening, but as a result, the value when used in other methods isn't set to the proper value. 我不太确定为什么会这样,但是结果是,在其他方法中使用时,该值未设置为正确的值。 Any help would be greatly appreciated! 任何帮助将不胜感激!

GetUserToken() does not return a user token. GetUserToken()不返回用户令牌。 It returns a Task which represents asynchronous work whose result is the user token. 它返回一个代表异步工作的Task ,其结果是用户令牌。

In essence, the following code: 本质上,以下代码:

var userToken = GetUserToken();

... is rather meaningless. ...毫无意义。

What you really want is: 您真正想要的是:

var userToken = await GetUserToken();
// Do something with the token.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM