Windows 通过 Azure Active Directory 表单身份验证

Windows forms Authentication via Azure Active Directory

在阅读文章 Azure Active Directory 时,我遇到了以下代码:

   string authority = "https://login.windows.net/winsmartstest.onmicrosoft.com";
        string resourceURI = "https://winsmartstest.onmicrosoft.com/MyWebAPI";
        string clientID = "9329c7a4-2d61-467b-94b8-c5ce67cca6c3";
        Uri returnURI = new Uri("http://doesntreallymatter");

        AuthenticationContext authContext =
            new AuthenticationContext(authority);
        AuthenticationResult authResult =
            authContext.AcquireToken(resourceURI, clientID, returnURI);

        string authHeader = authResult.CreateAuthorizationHeader();

        // don't do this in prod
        System.Net.ServicePointManager.ServerCertificateValidationCallback =
            ((s, c, c2, se) => true);

        HttpClient client = new HttpClient();
        HttpRequestMessage request =
            new HttpRequestMessage(HttpMethod.Get, "https://localhost:44300/api/tasks");
        request.Headers.TryAddWithoutValidation("Authorization", authHeader);
        var response = await client.SendAsync(request);
        string responseString = await response.Content.ReadAsStringAsync();
        MessageBox.Show(responseString);

我收到以下错误:

Error 1 The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.
c:\users25\documents\visual studio 2013\Projects\webapi.test\WindowsFormsApplication1\Form1.cs 43 28 WindowsFormsApplication1

我做错了什么?

您的问题与 Azure AD 无关。这是因为您正在使用 await 而没有使用 async 方法。您可以将方法更改为 async,或者删除 await。如果删除await,则需要调用Result 属性 将返回的任务。删除 await 可能是让代码正常工作的最简单方法,但不是提高性能的最佳方法。

喜欢var response = client.SendAsync(request).Result;

这里有更多关于 async 和 await 的信息:https://msdn.microsoft.com/en-us/library/hh191443.aspx

抱歉,必须在事件中添加异步,给您带来麻烦 private async void button1_Click(object sender, EventArgs e) { }