2015-05-22 35 views
0

這似乎是一個非常容易的,但因爲我沒有exp異步太多,然後我來專家。如何獲得異步調用的結果?

我需要做一個REST調用,併爲它我需要一個授權令牌(承載令牌)

這已經是該做:

private static async Task<string> GetAppTokenAsync() 
{ 
    string clientId = ConfigurationManager.AppSettings["ida:ClientId"]; 
    string appKey = ConfigurationManager.AppSettings["ida:AppKey"]; 
    string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"]; 
    string tenant = ConfigurationManager.AppSettings["ida:Tenant"]; 
    string postLogoutRedirectUri = ConfigurationManager.AppSettings["ida:PostLogoutRedirectUri"]; 
    string azureAdGraphApiEndPoint = ConfigurationManager.AppSettings["ida:AzureAdGraphApiEndPoint"]; 
    // This is the resource ID of the AAD Graph API. We'll need this to request a token to call the Graph API. 
    string graphResourceId = ConfigurationManager.AppSettings["ida:GraphResourceId"]; 

    string Authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant); 

    // Instantiate an AuthenticationContext for my directory (see authString above). 
    AuthenticationContext authenticationContext = new AuthenticationContext(Authority, false); 

    // Create a ClientCredential that will be used for authentication. 
    // This is where the Client ID and Key/Secret from the Azure Management Portal is used. 
    ClientCredential clientCred = new ClientCredential(clientId, appKey); 

    // Acquire an access token from Azure AD to access the Azure AD Graph (the resource) 
    // using the Client ID and Key/Secret as credentials. 
    AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenAsync(graphResourceId, clientCred); 

    // Return the access token. 
    return authenticationResult.AccessToken; 
} 

然而,從主叫方法,這與等候lambda表達式,我不知道怎麼去那個結果的引用,並放入的HTTPHeader

public ActionResult TestRestCall() 
{ 
    Uri serviceRoot = new Uri(azureAdGraphApiEndPoint); 

    ActiveDirectoryClient adClient = new ActiveDirectoryClient(
    serviceRoot, 
    async() => await GetAppTokenAsync()); 

    Application app = (Application)adClient.Applications.Where(
     a => a.AppId == clientId).ExecuteSingleAsync().Result; 
    if (app == null) 
    { 
     throw new ApplicationException("Unable to get a reference to application in Azure AD."); 
    } 

    HttpClient hc = new HttpClient(); 
    hc.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(
     "Bearer", CODE HERE); 

} 

回答

1

你應該讓你的來電顯示功能異步,如:

public async Task<ActionResult> TestRestCall() 

然後調用您的異步方法:

var token = await GetAppTokenAsync(); 
ActiveDirectoryClient adClient = new ActiveDirectoryClient(
      serviceRoot, token);