HttpClient PostAsync() never return response

后端 未结 3 1728
-上瘾入骨i
-上瘾入骨i 2021-01-03 21:51

My problem is very similar to this question here. I have an AuthenticationService class that makes an HttpClient PostAsync() and never

相关标签:
3条回答
  • 2021-01-03 22:32

    Since you are using .Result or .Wait or await this will end up causing a deadlock in your code.

    you can use ConfigureAwait(false) in async methods for preventing deadlock

    like this:

    string responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
    

    you can use ConfigureAwait(false) wherever possible for Don't Block Async Code .

    0 讨论(0)
  • 2021-01-03 22:45

    Since you are using .Result, this will end up causing a deadlock in your code. The reason this is working in a console application is because console applications don't have contexts, but ASP.NET apps do (see Stephen Cleary's Don't Block on Async Code). You should make the Signin method in your controller async and await the call to _authenticationService.Authenticate to resolve the deadlock issue.

    0 讨论(0)
  • 2021-01-03 22:49

    In case someone comes and needs to see code I just change the controller to something like this:

        /***
        *** Added async and Task<ActionResult>
        ****/
        public async Task<ActionResult> Signin(User user)
        {
            //no token needed - we are requesting one
            // added await and remove .Result()
            Token token =  await _authenticationService.Authenticate(user, ApiUrls.Signin);
    
            return RedirectToAction("Index", "Dashboard", token.user);
        }
    

    Thank you all for your quick response!

    0 讨论(0)
提交回复
热议问题