【问题标题】:Windows forms Authentication via Azure Active Directory通过 Azure Active Directory 进行 Windows 窗体身份验证
【发布时间】:2016-03-16 22:01:07
【问题描述】:

在阅读文章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);

我收到以下错误:

错误 1 ​​'await' 运算符只能在异步方法中使用。考虑使用“异步”修饰符标记此方法并将其返回类型更改为“任务”。
c:\users\6025\documents\visual studio 2013\Projects\webapi.test\WindowsFormsApplication1\Form1.cs 43 28 WindowsFormsApplication1

我做错了什么?

【问题讨论】:

  • 错误信息非常简单。您需要将方法更改为async
  • 你能贴出你的整个方法的代码,包括方法签名吗?

标签: azure async-await office365 azure-active-directory


【解决方案1】:

您的问题与 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

【讨论】:

  • Removing await is probably the simplest way to get your code working --> 我认为这不会解决问题,因为被调用的方法 (ReadAsStringAsync) 是异步的。如果你不等待这个方法,你可能不会得到想要的结果。
  • 异步方法将返回一个任务。 Task 有一个 Result 属性,其中包含您想要的对象。
【解决方案2】:

很抱歉,必须在事件中添加异步 private async void button1_Click(object sender, EventArgs e) { }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-29
    • 2017-04-06
    • 2020-02-11
    • 1970-01-01
    • 1970-01-01
    • 2016-12-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多