Await kills process

后端 未结 2 1936
一生所求
一生所求 2021-01-19 07:46

I am trying to connect to Azure AD and I am using this code.

try
{
    var clientCredential = new ClientCredential(_clientId, _clientSecret);
    var authCon         


        
2条回答
  •  庸人自扰
    2021-01-19 08:47

    Update code so that it is async all the way through. Make sure that you are not mixing async and sync code higher up the call stack. Avoid using async void.

    public async Task SomeMethodAsync() {
        try {
            var clientCredential = new ClientCredential(_clientId, _clientSecret);
            var authContext = new AuthenticationContext(AuthUri + _tenant);
            var authResult = await authContext.AcquireTokenAsync(GraphUri,clientCredential);
            var authString = authResult.CreateAuthorizationHeader();
            var client = new HttpClient();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
            var request = new HttpRequestMessage {
                Method = HttpMethod.Get,
                RequestUri = _requestUri,
            };
            request.Headers.Add("Authorization", authString);
    
            using(var response = await client.SendAsync(request)) {
                return await response.Content.ReadAsStringAsync();
            }    
        } catch (Exception ex) {
           Console.WriteLine(ex);
        }
    }
    

提交回复
热议问题