将Microsoft.Graph与控制台应用程序一起使用

时间:2017-08-26 13:17:39

标签: c# azure outlook

我正在尝试复制Microsoft示例,以便将Outlook.COM与控制台应用程序一起使用。所以我创建了一个C#控制台应用程序并添加了所需的包:

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Microsoft.Graph" version="1.5.1" targetFramework="net461" />
  <package id="Microsoft.Graph.Core" version="1.6.1" targetFramework="net461" />
  <package id="Microsoft.Identity.Client" version="1.1.0-preview" targetFramework="net461" />
  <package id="Newtonsoft.Json" version="6.0.1" targetFramework="net461" />
  <package id="System.Net.Http" version="4.3.1" targetFramework="net461" />
  <package id="System.Security.Cryptography.Algorithms" version="4.3.0" targetFramework="net461" />
  <package id="System.Security.Cryptography.Encoding" version="4.3.0" targetFramework="net461" />
  <package id="System.Security.Cryptography.Primitives" version="4.3.0" targetFramework="net461" />
  <package id="System.Security.Cryptography.X509Certificates" version="4.3.0" targetFramework="net461" />
</packages>

我修改了我的主控台类:

using System;
using Microsoft.Identity.Client;

namespace OutlookCalIFConsole
{
    class Program
    {
        //Below is the clientId of your app registration. 
        //You have to replace the below with the Application Id for your app registration
        private static string ClientId = "xxxxx";

        public static PublicClientApplication PublicClientApp = new PublicClientApplication(ClientId);

        static void Main(string[] args)
        {
            Outlook oOutlook = new Outlook();

            oOutlook.AquireToken();
            if (oOutlook.ResultsText != "")
                Console.WriteLine(oOutlook.ResultsText);
        }
    }
}

我创建了Outlook课程:

using Microsoft.Identity.Client;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace OutlookCalIFConsole
{
    class Outlook
    {

        //Set the API Endpoint to Graph 'me' endpoint
        string _graphAPIEndpoint = "https://graph.microsoft.com/v1.0/me";

        //Set the scope for API call to user.read
        string[] _scopes = new string[] { "user.read" };

        public string ResultsText { get { return strResultsText; } }
        string strResultsText = "";

        public async void AquireToken()
        {
            AuthenticationResult authResult = null;

            try
            {
                if (authResult == null)
                {
                    authResult = await Program.PublicClientApp.AcquireTokenSilentAsync(_scopes, Program.PublicClientApp.Users.FirstOrDefault());
                }
            }
            catch (MsalUiRequiredException ex)
            {
                // A MsalUiRequiredException happened on AcquireTokenSilentAsync. This indicates you need to call AcquireTokenAsync to acquire a token
                System.Diagnostics.Debug.WriteLine($"MsalUiRequiredException: {ex.Message}");

                try
                {
                    authResult = await Program.PublicClientApp.AcquireTokenAsync(_scopes);
                }
                catch (MsalException msalex)
                {
                    strResultsText = $"Error Acquiring Token:{System.Environment.NewLine}{msalex}";
                }
            }
            catch (Exception ex)
            {
                strResultsText = $"Error Acquiring Token Silently:{System.Environment.NewLine}{ex}";
                return;
            }

            if (authResult != null)
            {
                strResultsText = await GetHttpContentWithToken(_graphAPIEndpoint, authResult.AccessToken);
                Console.WriteLine(strResultsText);

                DisplayBasicTokenInfo(authResult);

                SignOut();
                if (strResultsText != "")
                    Console.WriteLine(strResultsText);
            }
        }

        /// <summary>
        /// Perform an HTTP GET request to a URL using an HTTP Authorization header
        /// </summary>
        /// <param name="url">The URL</param>
        /// <param name="token">The token</param>
        /// <returns>String containing the results of the GET operation</returns>
        public async Task<string> GetHttpContentWithToken(string url, string token)
        {
            var httpClient = new System.Net.Http.HttpClient();
            System.Net.Http.HttpResponseMessage response;
            try
            {
                var request = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Get, url);
                //Add the token in Authorization header
                request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
                response = await httpClient.SendAsync(request);
                var content = await response.Content.ReadAsStringAsync();
                return content;
            }
            catch (Exception ex)
            {
                return ex.ToString();
            }
        }

        private void DisplayBasicTokenInfo(AuthenticationResult authResult)
        {
            string strTokenInfoText = "";
            if (authResult != null)
            {
                strTokenInfoText += $"Name: {authResult.User.Name}" + Environment.NewLine;
                strTokenInfoText += $"Username: {authResult.User.DisplayableId}" + Environment.NewLine;
                strTokenInfoText += $"Token Expires: {authResult.ExpiresOn.ToLocalTime()}" + Environment.NewLine;
                strTokenInfoText += $"Access Token: {authResult.AccessToken}" + Environment.NewLine;
                Console.WriteLine(strTokenInfoText);
            }
        }

        public void SignOut()
        {
            strResultsText = "";
            if (Program.PublicClientApp.Users.Any())
            {
                try
                {
                    Program.PublicClientApp.Remove(Program.PublicClientApp.Users.FirstOrDefault());
                    Console.WriteLine("User has signed-out");
                }
                catch (MsalException ex)
                {
                    strResultsText = $"Error signing-out user: {ex.Message}";
                }
            }
        }
    }
}

以上是基于WPF的示例。我只是调整了它,因为我认为对于控制台应用程序是好的。但是当我运行它时,我得到一个例外:

  

抛出异常:Microsoft.Identity.Client.dll中的“Microsoft.Identity.Client.MsalUiRequiredException”       抛出异常:mscorlib.dll中的“Microsoft.Identity.Client.MsalUiRequiredException”       抛出异常:mscorlib.dll中的“Microsoft.Identity.Client.MsalUiRequiredException”

我已阅读MsalUiRequiredException,可以理解的是:

  

此异常类用于通知开发人员,验证成功需要UI交互。

那么,我究竟应该如何让它发挥作用呢?我认为它会显示一个浏览器控件,其中包含用户与之交互所需的资源。

我无法弄清楚如何让它工作以便我可以进行身份​​验证。根据代码,一切都会好的。

更新

我尝试过改变:

static void Main(string[] args)
{
    Outlook oOutlook = new Outlook();

    new Task(oOutlook.AquireToken).Start();

    if (oOutlook.ResultsText != "")
        Console.WriteLine(oOutlook.ResultsText);
}

没有任何区别。

1 个答案:

答案 0 :(得分:3)

问题是AquireToken()被标记为async void,除非是事件处理程序,否则应该避免使用async void。由于调用Task方法,无法捕获异常。

此外,因为您没有等待创建的任务,所以在完成任务之前,您的应用程序完全可能已退出。

解决此问题的一种方法是让主应用创建Main并等待其完成。 async不能await,因此您需要明确阻止该任务,而不是使用static void Main(string[] args) { var program = new Program(); var task = Task.Run(program.Run); task.Wait(); }

Program

...然后将此新方法添加到private async Task Run() { Outlook oOutlook = new Outlook(); await oOutlook.AquireToken(); if (oOutlook.ResultsText != "") Console.WriteLine(oOutlook.ResultsText); }

AquireToken

更改public async void AquireToken() 签名:

public async Task AquireToken()  

...为:

{{1}}

现在,当您运行控制台应用程序时,您将看到登录窗口。在这里,您可以看到它已经提取了我的缓存帐户名称:

enter image description here

告诉我有关async / await

的更多信息