You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET 6.0 WebAPI引入Microsoft.Graph v5.18.0后类型加载失败问题

解决ASP.NET 6 Web API引入Microsoft.Graph v5.18.0后的TypeLoadException问题

问题场景

我有一个ASP.NET 6.0 Web API项目,引入了Microsoft.Graph v5.18.0包以注入Graph API客户端,并在部分控制器中调用Graph接口。但添加该包后,在Startup.cs文件执行app.UseEndpoints(e=> e.MapControllers())时出现以下错误:

System.Reflection.ReflectionTypeLoadException: Unable to load one or more of the requested types.
Could not load type 'Microsoft.Graph.Device' from assembly 'Microsoft.Graph, Version=5.18.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'.
Could not load type 'Microsoft.Graph.Device' from assembly 'Microsoft.Graph, Version=5.18.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'.
   at System.Reflection.RuntimeModule.GetTypes(RuntimeModule module)
   at System.Reflection.RuntimeAssembly.get_DefinedTypes()
   at Microsoft.AspNetCore.Mvc.ApplicationParts.AssemblyPart.get_Types()
   at Microsoft.AspNetCore.Mvc.Controllers.ControllerFeatureProvider.PopulateFeature(IEnumerable`1 parts, ControllerFeature feature)
   at Microsoft.AspNetCore.Mvc.ApplicationParts.ApplicationPartManager.PopulateFeature[TFeature](TFeature feature)
   at Microsoft.AspNetCore.Mvc.ApplicationModels.ControllerActionDescriptorProvider.GetControllerTypes()
   at Microsoft.AspNetCore.Mvc.ApplicationModels.ControllerActionDescriptorProvider.GetDescriptors()
   at Microsoft.AspNetCore.Mvc.ApplicationModels.ControllerActionDescriptorProvider.OnProvidersExecuting(ActionDescriptorProviderContext context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.DefaultActionDescriptorCollectionProvider.UpdateCollection()
   at Microsoft.AspNetCore.Mvc.Infrastructure.DefaultActionDescriptorCollectionProvider.Initialize()
   at Microsoft.AspNetCore.Mvc.Routing.ActionEndpointDataSourceBase.<>c__DisplayClass11_0.<Subscribe>b__0()
   at Microsoft.Extensions.Primitives.ChangeToken.OnChange(Func`1 changeTokenProducer, Action changeTokenConsumer)
   at Microsoft.AspNetCore.Mvc.Routing.ActionEndpointDataSourceBase.Subscribe()
   at Microsoft.AspNetCore.Mvc.Routing.ControllerActionEndpointDataSource..ctor(ControllerActionEndpointDataSourceIdProvider dataSourceIdProvider, IActionDescriptorCollectionProvider actions, ActionEndpointFactory endpointFactory, OrderedEndpointsSequenceProvider orderSequence)
   at Microsoft.AspNetCore.Builder.ControllerEndpointRouteBuilderExtensions.GetOrCreateDataSource(IEndpointRouteBuilder endpoints)
   at Microsoft.AspNetCore.Builder.ControllerEndpointRouteBuilderExtensions.MapControllers(IEndpointRouteBuilder endpoints)
   at Synergix.LEDR.API.Startup.<>c.<Configure>b__5_0(IEndpointRouteBuilder endpoint) in C:\Users\96170\source\repos\LEDR\src\ServerSide\APIs\Synergix.LEDR.API\Startup.cs:line 140
   at Microsoft.AspNetCore.Builder.EndpointRoutingApplicationBuilderExtensions.UseEndpoints(IApplicationBuilder builder, Action`1 configure)
   at Synergix.LEDR.API.Startup.Configure(IApplicationBuilder app, IWebHostEnvironment env) in C:\Users\96170\source\repos\LEDR\src\ServerSide\APIs\Synergix.LEDR.API\Startup.cs:line 140
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Span`1& arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at Microsoft.AspNetCore.Hosting.ConfigureBuilder.Invoke(Object instance, IApplicationBuilder builder)
   at Microsoft.AspNetCore.Hosting.ConfigureBuilder.<>c__DisplayClass4_0.<Build>b__0(IApplicationBuilder builder)
   at Microsoft.AspNetCore.Hosting.ConventionBasedStartup.Configure(IApplicationBuilder app)
   at Microsoft.AspNetCore.Mvc.Filters.MiddlewareFilterBuilderStartupFilter.<>c__DisplayClass0_0.<Configure>g__MiddlewareFilterBuilder|0(IApplicationBuilder builder)
   at Microsoft.ApplicationInsights.AspNetCore.ApplicationInsightsStartupFilter.<>c__DisplayClass2_0.<Configure>b__0(IApplicationBuilder app)
   at Microsoft.AspNetCore.Server.IIS.Core.IISServerSetupFilter.<>c__DisplayClass2_0.<Configure>b__0(IApplicationBuilder app)
   at Microsoft.AspNetCore.HostFilteringStartupFilter.<>c__DisplayClass0_0.<Configure>b__0(IApplicationBuilder app)
   at Microsoft.AspNetCore.Hosting.WebHost.BuildApplication()
   at Microsoft.AspNetCore.Hosting.WebHost.StartAsync(CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Hosting.WebHostExtensions.RunAsync(IWebHost host, CancellationToken token, String startupMessage)
   at Microsoft.AspNetCore.Hosting.WebHostExtensions.RunAsync(IWebHost host, CancellationToken token, String startupMessage)
   at Microsoft.AspNetCore.Hosting.WebHostExtensions.RunAsync(IWebHost host, CancellationToken token)
   at Microsoft.AspNetCore.Hosting.WebHostExtensions.Run(IWebHost host)
   at Synergix.LEDR.API.Program.Main(String[] args) in C:\Users\96170\source\repos\LEDR\src\ServerSide\APIs\Synergix.LEDR.API\Program.cs:line 20
System.TypeLoadException: Could not load type 'Microsoft.Graph.Device' from assembly 'Microsoft.Graph, Version=5.18.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'.

我并未在任何地方使用Microsoft.Graph.Device类型,以下是可行的解决方法:


解决方法

1. 清理并重建项目

项目的bin/obj目录可能存在缓存的旧dll文件,导致类型加载冲突:

  • 在Visual Studio中右键项目 → 清理,再右键 → 生成
  • 或手动删除项目根目录下的bin和obj文件夹,执行命令:
    dotnet clean
    dotnet build
    

2. 统一Microsoft.Graph相关依赖版本

Microsoft.Graph v5.x拆分了核心功能和实体类型,可能存在间接依赖版本不匹配:

  • 打开NuGet包管理器,检查所有Microsoft.Graph系列包(如Microsoft.Graph.Core)的版本,确保与v5.18.0配套
  • 编辑项目的.csproj文件,显式指定所有相关包的版本,避免自动解析时出现版本差异:
    <ItemGroup>
      <PackageReference Include="Microsoft.Graph" Version="5.18.0" />
      <PackageReference Include="Microsoft.Graph.Core" Version="2.0.14" />
    </ItemGroup>
    

3. 排除Microsoft.Graph程序集的控制器扫描

ASP.NET Core启动时会扫描所有程序集查找控制器,而Microsoft.Graph v5.x中Device类型可能已迁移到其他包,导致扫描失败。可以在ConfigureServices中排除该程序集:

using Microsoft.AspNetCore.Mvc.ApplicationParts;
using System.Reflection;

public void ConfigureServices(IServiceCollection services)
{
    // ...其他服务配置

    // 移除Microsoft.Graph程序集的扫描
    var graphAssembly = Assembly.Load("Microsoft.Graph");
    services.Configure<MvcOptions>(options =>
    {
        var targetPart = options.ApplicationParts.FirstOrDefault(p => p.Name.Equals(graphAssembly.GetName().Name));
        if (targetPart != null)
        {
            options.ApplicationParts.Remove(targetPart);
        }
    });
}

4. 更新到最新稳定版Microsoft.Graph

v5.18.0可能存在已知的类型定义问题,尝试更新到最新稳定版本:

dotnet add package Microsoft.Graph --version [最新稳定版本号]

5. 检查旧版本残留

确保项目中没有旧版本的Microsoft.Graph引用:

  • 检查.csproj文件,移除任何旧的PackageReference条目
  • 检查输出目录(bin),确保只有v5.18.0版本的Microsoft.Graph.dll存在

内容的提问来源于stack exchange,提问作者Mohammad Fneish

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 03:24:50