使用Microsoft.Graph在C#控制台应用程序中列出日历

使用Microsoft.Graph在C#控制台应用程序中列出日历,c#,console-application,microsoft-graph-api,C#,Console Application,Microsoft Graph Api,我在这里真的陷入了困境(我只是不明白如何转移我在这里看到的东西: 在我的C#控制台应用程序的上下文中 我做了这么多: //Set the scope for API call to user.read string[] _scopes = new string[] { "user.read", "calendars.read" }; 并确认当我登录时,它确实要求访问用户日历 但我不知道从这里走到哪里。我在示例代码中有: private void DisplayBasicTokenIn

我在这里真的陷入了困境(我只是不明白如何转移我在这里看到的东西:

在我的C#控制台应用程序的上下文中

我做了这么多:

//Set the scope for API call to user.read
string[] _scopes = new string[] { "user.read",  "calendars.read" };
并确认当我登录时,它确实要求访问用户日历

但我不知道从这里走到哪里。我在示例代码中有:

   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 async Task 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}";
    }

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

        DisplayBasicTokenInfo(authResult);

        GraphServiceClient graphClient = new GraphServiceClient(
             new DelegateAuthenticationProvider(
                 (requestMessage) =>
                 {
                     // Append the access token to the request.
                     requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", authResult.AccessToken);
                     return Task.FromResult(0);
                 }));

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

        DisplayBasicTokenInfo(authResult);

        GraphServiceClient graphClient = new GraphServiceClient(
                 new DelegateAuthenticationProvider(
                     (requestMessage) =>
                     {
                         // Append the access token to the request.
                         requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", authResult.AccessToken);
                         return Task.FromResult(0);
                     }));

        var calendars = await graphClient
                             .Me
                             .Calendars
                             .Request()
                             .GetAsync();
        Console.WriteLine(calendars.Count.ToString());
        List<Calendar> listCalendars = calendars.ToList();
        foreach(Calendar oCalendar in listCalendars)
        {
            Console.WriteLine(oCalendar.Name);
        }
        SignOut();
        if (strResultsText != "")
            Console.WriteLine(strResultsText);
    }
如您所见,我添加了以下代码:

GraphServiceClient graphClient = new GraphServiceClient(
     new DelegateAuthenticationProvider(
         (requestMessage) =>
         {
             // Append the access token to the request.
             requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", authResult.AccessToken);
             return Task.FromResult(0);
         }));
我在
注销
上设置了一个断点,但无法使其工作

我希望能够使用
graphClient.me.Calendars

困惑

更新 我试着看了看“阅读我”。也许我只是在错误的地方做事情?但当我设置断点时:

这不是我所期望的

更新2 我调整代码如下:

public async Task 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}";
    }

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

        DisplayBasicTokenInfo(authResult);

        GraphServiceClient graphClient = new GraphServiceClient(
             new DelegateAuthenticationProvider(
                 (requestMessage) =>
                 {
                     // Append the access token to the request.
                     requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", authResult.AccessToken);
                     return Task.FromResult(0);
                 }));

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

        DisplayBasicTokenInfo(authResult);

        GraphServiceClient graphClient = new GraphServiceClient(
                 new DelegateAuthenticationProvider(
                     (requestMessage) =>
                     {
                         // Append the access token to the request.
                         requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", authResult.AccessToken);
                         return Task.FromResult(0);
                     }));

        var calendars = await graphClient
                             .Me
                             .Calendars
                             .Request()
                             .GetAsync();
        Console.WriteLine(calendars.Count.ToString());
        List<Calendar> listCalendars = calendars.ToList();
        foreach(Calendar oCalendar in listCalendars)
        {
            Console.WriteLine(oCalendar.Name);
        }
        SignOut();
        if (strResultsText != "")
            Console.WriteLine(strResultsText);
    }

为了他人的利益,我是这样让它工作的:

public bool InitAuthenticatedClientAsync()
{
    bool bSuccess = true;

    _graphClient = new GraphServiceClient(
        new DelegateAuthenticationProvider(
            async (requestMessage) =>
            {
                try
                {
                    var accounts = await PublicClientApp.GetAccountsAsync();
                    // See: https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/MSAL.NET-3-released#acquiring-a-token-also-got-simpler
                    _AuthResult = await PublicClientApp.AcquireTokenSilent(_Scopes, accounts.FirstOrDefault()).ExecuteAsync();
                }
                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
                    {
                        // See: https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/MSAL.NET-3-released#acquiring-a-token-also-got-simpler
                        _AuthResult = await PublicClientApp.AcquireTokenInteractive(_Scopes).ExecuteAsync();
                    }
                    catch (MsalException msalex)
                    {
                        SimpleLog.Log(msalex);
                        Console.WriteLine("GetAuthenticatedClientAsync: Acquire token error. See log.");
                        bSuccess = false;
                    }
                }
                catch (Exception ex)
                {
                    SimpleLog.Log(ex);
                    Console.WriteLine("GetAuthenticatedClientAsync: Acquire token silently error. See log.");
                    bSuccess = false;
                }

                if(bSuccess)
                {
                    // Append the access token to the request.
                    requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", _AuthResult.AccessToken);

                    // Get event times in the current time zone.
                    requestMessage.Headers.Add("Prefer", "outlook.timezone=\"" + TimeZoneInfo.Local.Id + "\"");
                }
            }));

    return bSuccess;
}

public async Task<bool> BuildCalendarsList()
{
    bool bSuccess = true;

    if (_graphClient == null)
        return false;

    try
    {
        var calendars = await _graphClient
                             .Me
                             .Calendars
                             .Request()
                             .GetAsync();


        foreach (Calendar oCalendar in calendars)
        {
            _CalendarInfo.AddCalendarEntry(oCalendar.Name, oCalendar.Id);
        }

        bSuccess = SaveCalendarInfo();
    }
    catch (Exception ex)
    {
        SimpleLog.Log(ex);
        Console.WriteLine("BuildCalendarsList: See error log.");
        bSuccess = false;
    }

    return bSuccess;
}
public bool initauthenticatedclientsync()
{
bool bSuccess=true;
_graphClient=新的GraphServiceClient(
新的DelegateAuthenticationProvider(
异步(请求消息)=>
{
尝试
{
var accounts=await PublicClientApp.GetAccountsAsync();
//见:https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/MSAL.NET-3-released#acquiring-a-token-allow-get-simpler
_AuthResult=await PublicClientApp.AcquireTokenSilent(_作用域,accounts.FirstOrDefault()).ExecuteAsync();
}
捕获(MsalUiRequiredException ex)
{
//AcquireTokenSilentAsync上发生MsalUiRequiredException。这表示需要调用AcquireTokenAsync来获取令牌
System.Diagnostics.Debug.WriteLine($“MsalUiRequiredException:{ex.Message}”);
尝试
{
//见:https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/MSAL.NET-3-released#acquiring-a-token-allow-get-simpler
_AuthResult=await PublicClientApp.AcquireTokenInteractive(_Scopes.ExecuteAsync();
}
捕获(MsalException-msalex)
{
SimpleLog.Log(msalex);
WriteLine(“GetAuthenticatedClientSync:获取令牌错误。请参阅日志”);
b成功=错误;
}
}
捕获(例外情况除外)
{
SimpleLog.Log(ex);
WriteLine(“GetAuthenticatedClientSync:Acquire-token-Sil默错误。请参阅日志”);
b成功=错误;
}
如果(b成功)
{
//将访问令牌附加到请求。
requestMessage.Headers.Authorization=新的AuthenticationHeaderValue(“承载者”、\u AuthResult.AccessToken);
//获取当前时区中的事件时间。
requestMessage.Headers.Add(“首选”、“outlook.timezone=\”“+TimeZoneInfo.Local.Id+”\”);
}
}));
返回b成功;
}
公共异步任务BuildCalendarsList()
{
bool bSuccess=true;
if(_graphClient==null)
返回false;
尝试
{
var日历=等待图形客户端
我
.日历
.Request()
.GetAsync();
foreach(日历中的日历oCalendar)
{
_CalendarInfo.AddCalendarEntry(oCalendar.Name,oCalendar.Id);
}
bSuccess=SaveCalendarInfo();
}
捕获(例外情况除外)
{
SimpleLog.Log(ex);
WriteLine(“BuildCalendarsList:请参阅错误日志”);
b成功=错误;
}
返回b成功;
}

为了其他人的利益,我是这样让它工作的:

public bool InitAuthenticatedClientAsync()
{
    bool bSuccess = true;

    _graphClient = new GraphServiceClient(
        new DelegateAuthenticationProvider(
            async (requestMessage) =>
            {
                try
                {
                    var accounts = await PublicClientApp.GetAccountsAsync();
                    // See: https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/MSAL.NET-3-released#acquiring-a-token-also-got-simpler
                    _AuthResult = await PublicClientApp.AcquireTokenSilent(_Scopes, accounts.FirstOrDefault()).ExecuteAsync();
                }
                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
                    {
                        // See: https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/MSAL.NET-3-released#acquiring-a-token-also-got-simpler
                        _AuthResult = await PublicClientApp.AcquireTokenInteractive(_Scopes).ExecuteAsync();
                    }
                    catch (MsalException msalex)
                    {
                        SimpleLog.Log(msalex);
                        Console.WriteLine("GetAuthenticatedClientAsync: Acquire token error. See log.");
                        bSuccess = false;
                    }
                }
                catch (Exception ex)
                {
                    SimpleLog.Log(ex);
                    Console.WriteLine("GetAuthenticatedClientAsync: Acquire token silently error. See log.");
                    bSuccess = false;
                }

                if(bSuccess)
                {
                    // Append the access token to the request.
                    requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", _AuthResult.AccessToken);

                    // Get event times in the current time zone.
                    requestMessage.Headers.Add("Prefer", "outlook.timezone=\"" + TimeZoneInfo.Local.Id + "\"");
                }
            }));

    return bSuccess;
}

public async Task<bool> BuildCalendarsList()
{
    bool bSuccess = true;

    if (_graphClient == null)
        return false;

    try
    {
        var calendars = await _graphClient
                             .Me
                             .Calendars
                             .Request()
                             .GetAsync();


        foreach (Calendar oCalendar in calendars)
        {
            _CalendarInfo.AddCalendarEntry(oCalendar.Name, oCalendar.Id);
        }

        bSuccess = SaveCalendarInfo();
    }
    catch (Exception ex)
    {
        SimpleLog.Log(ex);
        Console.WriteLine("BuildCalendarsList: See error log.");
        bSuccess = false;
    }

    return bSuccess;
}
public bool initauthenticatedclientsync()
{
bool bSuccess=true;
_graphClient=新的GraphServiceClient(
新的DelegateAuthenticationProvider(
异步(请求消息)=>
{
尝试
{
var accounts=await PublicClientApp.GetAccountsAsync();
//见:https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/MSAL.NET-3-released#acquiring-a-token-allow-get-simpler
_AuthResult=await PublicClientApp.AcquireTokenSilent(_作用域,accounts.FirstOrDefault()).ExecuteAsync();
}
捕获(MsalUiRequiredException ex)
{
//AcquireTokenSilentAsync上发生MsalUiRequiredException。这表示需要调用AcquireTokenAsync来获取令牌
System.Diagnostics.Debug.WriteLine($“MsalUiRequiredException:{ex.Message}”);
尝试
{
//见:https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/MSAL.NET-3-released#acquiring-a-token-allow-get-simpler
_AuthResult=await PublicClientApp.AcquireTokenInteractive(_Scopes.ExecuteAsync();
}
捕获(MsalException-msalex)
{
SimpleLog.Log(msalex);
WriteLine(“GetAuthenticatedClientSync:获取令牌错误。请参阅日志”);
b成功=错误;
}
}
捕获(例外情况除外)
{
SimpleLog.Log(ex);
控制台写入线