如何在ASP.NET Core 6.0中正确注册GraphServiceClient
ASP.NET Core 6.0中正确注册GraphServiceClient的方法
问题场景
在控制器中注入GraphServiceClient并调用_client.Me.GetAsync()获取用户部门信息时,抛出以下错误:
InvalidOperationException: Unable to resolve service for type 'Microsoft.Graph.GraphServiceClient' while attempting to activate 'ExternalApp.Areas.Budget.Controllers.Controller'
控制器代码如下:
namespace ExternalApp.Areas.Budget.Controllers { public class Controller : BaseController { private readonly BudgetDbContext _db; private readonly GraphServiceClient _client; public Controller( ILogger<BaseController> logger, BudgetDbContext db, GraphServiceClient client) : base(logger) { _db = db; _client = client; } public async Task<JsonResult> GetVehicleAcquisitions() { var data = _db.VehicleAcquisitions.AsQueryable(); var user = await _client.Me.GetAsync(); if (User.IsInRole("Administrator")) data = _db.VehicleAcquisitions .Where(x => x.GlSegment3.SSegment3Desc .Contains(user.Department)) .AsQueryable(); // Other code } } }
当前Program.cs代码:
var builder = WebApplication.CreateBuilder(args); builder.Host.ConfigureServices((hostContext, services) => { services.AddMicrosoftIdentityWebAppAuthentication(hostContext.Configuration); }); builder.Services.AddControllersWithViews(); builder.Services.AddDbContext<BudgetDbContext>(options => options.UseSqlServer(builder.Configuration .GetConnectionString("BudgetEntities")) .UseLazyLoadingProxies() ); var app = builder.Build(); if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); app.Run();
解决方案
1. 安装必要的NuGet包
确保已安装以下包:
Microsoft.GraphMicrosoft.Identity.Web.MicrosoftGraph
可通过命令行安装:
Install-Package Microsoft.Graph Install-Package Microsoft.Identity.Web.MicrosoftGraph
2. 修改Program.cs注册GraphServiceClient
在AddMicrosoftIdentityWebAppAuthentication之后,添加Graph服务的注册,利用Microsoft Identity Web的扩展方法简化配置:
var builder = WebApplication.CreateBuilder(args); builder.Host.ConfigureServices((hostContext, services) => { services.AddMicrosoftIdentityWebAppAuthentication(hostContext.Configuration) // 启用下游API的令牌获取 .EnableTokenAcquisitionToCallDownstreamApi() // 注册GraphServiceClient,读取配置文件中的Graph参数 .AddMicrosoftGraph(hostContext.Configuration.GetSection("MicrosoftGraph")) // 使用内存缓存存储令牌 .AddInMemoryTokenCaches(); }); builder.Services.AddControllersWithViews(); builder.Services.AddDbContext<BudgetDbContext>(options => options.UseSqlServer(builder.Configuration .GetConnectionString("BudgetEntities")) .UseLazyLoadingProxies() ); // 剩余代码保持不变 var app = builder.Build(); if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); app.Run();
3. 配置appsettings.json中的Graph参数
在appsettings.json中添加Microsoft Graph的配置节点:
"MicrosoftGraph": { "BaseUrl": "https://graph.microsoft.com/v1.0", "Scopes": "User.Read" }
Scopes需包含实际业务需要的权限,获取用户部门仅需User.Read即可。
4. 验证控制器使用
控制器中的注入和调用代码无需修改,现在GraphServiceClient可被正常解析,_client.Me.GetAsync()能正确获取用户信息。
内容的提问来源于stack exchange,提问作者csharpdev
相关产品推荐
相关产品推荐

