ASP.NET Core MVC中Microsoft Graph客户端类型加载异常求助
问题:从Entra获取用户属性时遇到TypeLoadException错误
背景说明
- 最初计划使用
graphClient.Me.GetAsync()获取Entra用户属性 - 更新:需要获取
graphClient.Me.GetAsync()无法返回的属性,因此改用以下代码:
怀疑该功能仅支持Microsoft.Graph 5.61版本,但不确定var result = await graphClient.Users["{user-id}"].GetAsync((requestConfiguration) => { requestConfiguration.QueryParameters.Select = new string []{ "displayName","givenName","postalCode","identities" }; });
错误信息
在Visual Studio中运行项目,输入Entra凭据后抛出异常:
处理请求时发生未处理的异常。
TypeLoadException: 无法从程序集'Microsoft.Graph.Core, Version=3.1.22.0, Culture=neutral, PublicKeyToken=xxxxxxxxxxxx'加载类型'Microsoft.Graph.IAuthenticationProviderOption'。
项目配置详情
已安装的NuGet包
Microsoft.Graph v.5.61 Microsoft.Identity.Web 3.2.2 Microsoft.Identity.Web.MicrosoftGraph v. 3.2.2
appsettings.json配置
{ "AzureAd": { "Instance": "https://login.microsoftonline.com/", "Domain": "yourdomain.onmicrosoft.com", "TenantId": "your-tenant-id", "ClientId": "your-client-id", "ClientSecret": "your-client-secret", "CallbackPath": "/signin-oidc" } }
Program.cs代码
using Microsoft.Identity.Web; using Microsoft.AspNetCore.Authentication.OpenIdConnect; var builder = WebApplication.CreateBuilder(args); // 添加身份验证和Microsoft Identity builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme) .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd")); // 添加Graph API客户端 builder.Services.AddMicrosoftGraph(options => { options.Scopes = "User.Read"; // 确保此范围已在Azure门户中授予 }); builder.Services.AddControllersWithViews(); var app = builder.Build(); // 配置HTTP请求管道 if (app.Environment.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { 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();
控制器代码
[Authorize] public class HomeController : Controller { private readonly GraphServiceClient _graphClient; public HomeController(GraphServiceClient graphClient) { _graphClient = graphClient; } public async Task<IActionResult> Index() { // 获取用户信息 var user = await _graphClient.Me.GetAsync(); // 获取用户邮箱 var email = user.Mail ?? user.UserPrincipalName; ViewBag.Email = email; return View(); } }
csproj文件内容
<Project Sdk="Microsoft.NET.Sdk.Web"> <PropertyGroup> <TargetFramework>net8.0</TargetFramework> <Nullable>enable</Nullable> <ImplicitUsings>enable</ImplicitUsings> </PropertyGroup> <ItemGroup> <PackageReference Include="Microsoft.Graph" Version="5.61.0" /> <PackageReference Include="Microsoft.Identity.Web" Version="3.2.2" /> <PackageReference Include="Microsoft.Identity.Web.GraphServiceClient" Version="3.2.2" /> <PackageReference Include="Microsoft.Identity.Web.MicrosoftGraph" Version="3.2.2" /> </ItemGroup> </Project>
疑问
请问我哪里操作有误?已经尝试过更换包版本、修改Program.cs中的代码,但问题仍未解决。
内容的提问来源于stack exchange,提问作者Baze2024
相关产品推荐
相关产品推荐

