如何在 C# 中使用 Microsoft Graph 捕获错误

问题描述 投票:0回答:1

我设法实现 Microsoft Graph 通过

InteractiveBrowserCredential
身份验证检索电子邮件。经过一番努力通过 Graph Explorer 配置所有内容后,一切正常(我什至不记得我是如何做到的)。

基本上,我会被重定向到网络浏览器,要求我单击我想要用于授权的电子邮件。尽管如此,我想在关闭选项卡或单击错误的电子邮件时捕获。

有人可以告诉我如何捕获失败的身份验证吗?好像卡在了

await user.MailFolders.GetAsync()

var appSettings = _configuration.GetSection("AppSettings");

var tenantId = appSettings["Microsoft Graph:tenant id"];
var clientId = appSettings["Microsoft Graph:client id"];

var redirectUri = new Uri("http://localhost");

var options = new InteractiveBrowserCredentialOptions
{
    TenantId = tenantId,
    ClientId = clientId,
    AuthorityHost = AzureAuthorityHosts.AzurePublicCloud,
    RedirectUri = redirectUri,
};
            
var interactiveCredential = new InteractiveBrowserCredential(options);

var scopes = new []
{
    "Mail.Read"
};

var graphServiceClient = new GraphServiceClient(interactiveCredential, scopes);

try
{
    var user = graphServiceClient.Me;

    var mailFolders = await user.MailFolders.GetAsync(); // Gets stuck here even if the authentication fails.

    // ...
}
catch (Exception ex)
{
    return;
}
azure authentication error-handling microsoft-graph-api interactive
1个回答
0
投票

要获取登录用户的邮件文件夹,请确保授予

Mail.Read
委派 API 权限:

enter image description here

使用以下代码:

using Microsoft.Graph;
using Azure.Identity;
using Microsoft.Graph.Models.ODataErrors;

var tenantId = "TenantID";
var clientId = "ClientID";
var redirectUri = new Uri("http://localhost");

var options = new InteractiveBrowserCredentialOptions
{
    TenantId = tenantId,
    ClientId = clientId,
    AuthorityHost = AzureAuthorityHosts.AzurePublicCloud,
    RedirectUri = redirectUri,
};

var interactiveCredential = new InteractiveBrowserCredential(options);
var scopes = new[] { "Mail.Read" };
var graphServiceClient = new GraphServiceClient(interactiveCredential, scopes);

try
{
    var user = graphServiceClient.Me;

    var mailFoldersResponse = await user.MailFolders.GetAsync();

    var mailFolders = mailFoldersResponse.Value;

    foreach (var folder in mailFolders)
    {
        Console.WriteLine($"Folder Name: {folder.DisplayName}");
    }
}
catch (ODataError odataError)
{
    Console.WriteLine($"OData Error Message: {odataError.Error.Message}");
    Console.WriteLine($"OData Error Code: {odataError.Error.Code}");
}
catch (Exception ex)
{
    Console.WriteLine($"Unexpected Error: {ex.Message}");
}

enter image description here

确保将应用程序标记为公开:

enter image description here

参考:

列出邮件文件夹-Microsoft Graph v1.0 |微软

© www.soinside.com 2019 - 2024. All rights reserved.