如何为Microsoft Graph Client设置默认请求选项
我用Microsoft Graph SDK搭建了ASP.NET Core 6 Web API,现在所有Graph请求都要手动添加以下代码:
.WithAppOnly() .WithMaxRetry(10) .WithMaxRetry(new TimeSpan(0, 0, 0, 10, 0))
示例调用代码:
await graphServiceClient.Teams[teamId].Channels[channelId].Tabs .Request() .WithAppOnly() .WithMaxRetry(10) .WithMaxRetry(new TimeSpan(0, 0, 0, 10, 0)) .GetAsync()
请问能否在Program.cs中全局配置这些设置,避免每次调用都重复编写?
当前Program.cs中的Graph服务配置:
//add Graph service builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddMicrosoftIdentityWebApi(builder.Configuration) .EnableTokenAcquisitionToCallDownstreamApi() .AddMicrosoftGraph(builder.Configuration.GetSection("Graph")) .AddInMemoryTokenCaches();
AppSettings.json配置内容:
{ "AzureAd": { "Instance": "https://login.microsoftonline.com/", "Domain": "<< domain >>", "TenantId": " <<tenant id >>", "ClientId": " << client id >>", "ClientSecret": " << client secret >>" }, "Graph": { "BaseUrl": "https://graph.microsoft.com/v1.0", "Scopes": "https://graph.microsoft.com/.default" }, "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "AllowedHosts": "*" }
解决方案
可以通过自定义GraphServiceClient的全局配置来实现,不用每次请求重复编写代码,具体步骤如下:
1. 修改Program.cs中的Graph服务注册
替换原有的.AddMicrosoftGraph(builder.Configuration.GetSection("Graph")),改用带配置委托的重载,直接设置全局重试策略:
//add Graph service builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddMicrosoftIdentityWebApi(builder.Configuration) .EnableTokenAcquisitionToCallDownstreamApi() .AddMicrosoftGraph(options => { options.BaseUrl = builder.Configuration["Graph:BaseUrl"]; // 全局设置最大重试次数 options.MaxRetry = 10; // 全局设置最大重试总时长(10秒) options.MaxRetryDuration = TimeSpan.FromSeconds(10); }) .AddInMemoryTokenCaches();
2. 关于.WithAppOnly()的全局处理
.WithAppOnly()用于指定使用应用权限模式,由于你的配置中Graph:Scopes已经设置为https://graph.microsoft.com/.default(应用权限的默认范围),且使用了客户端密钥(ClientSecret),SDK会自动采用客户端凭据流(应用权限模式)获取令牌,因此不需要每次调用都手动添加.WithAppOnly()。
如果确实需要显式确保全局使用应用模式,可以创建一个简单的扩展方法来统一处理:
public static class GraphRequestExtensions { public static IBaseRequest WithAppOnlyDefaults(this IBaseRequest request) { return request.WithAppOnly(); } }
之后调用时只需添加.WithAppOnlyDefaults()即可,但通常这一步可以省略。
3. 验证效果
修改完成后,所有通过依赖注入获取的GraphServiceClient发起的请求,都会自动应用你配置的重试次数和重试时长,无需再手动添加.WithMaxRetry()相关代码。
内容的提问来源于stack exchange,提问作者Michael Kubala

