如何获得异步调用的结果?

时间:2015-05-22 23:12:49

标签: c# asp.net asp.net-mvc

这似乎很简单,但由于我没有过多的异步,所以我来找专家。

我需要进行休息通话,为此我需要一个授权令牌。(不记名令牌)

这已经完成了:

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;
}

但是,从调用方法,这是一个带有await的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 个答案:

答案 0 :(得分:1)

你应该让你的调用者函数Async像:

public async Task<ActionResult> TestRestCall()

然后调用你的异步方法:

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