简体   繁体   中英

ASP.NET Task Async WaitingForActivation

I am trying to send a post request to a third party API and retrieve the 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. However, when I do a method call to this method and step through it in the debugger, the value of the Usertoken is set

var userToken = GetUserToken(); 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. It returns a Task which represents asynchronous work whose result is the user token.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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