如何从ASP.NET Core WebAPI二进制文件中提取Controller类方法列表
解决方案
方案1:修改WebAPI项目配置适配原有代码
这是改动最小的方案,只需要调整WebAPI项目的生成配置,原有加载程序集的代码完全不需要修改。
在你的ASP.NET Core WebAPI项目的.csproj文件中,加入以下配置节点:
<PropertyGroup> <!-- 强制发布时复制所有依赖的dll到输出目录 --> <CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies> </PropertyGroup>
重新编译发布WebAPI项目后,输出目录会包含所有运行所需的dll,你原来的加载逻辑可以直接正常运行。
方案2:WPF端适配.NET5+程序集加载规则
不需要修改WebAPI项目的任何配置,直接在WPF端调整程序集加载逻辑,使用.NET Core 3.0+ 提供的AssemblyDependencyResolver自动解决依赖查找问题,代码示例如下:
using System.Reflection; using System.Runtime.Loader; using Microsoft.AspNetCore.Mvc; // 替换为你发布的WebAPI主程序集路径 string webApiAssemblyPath = @"D:\publish\MyTestApp.WebApi.dll"; // 初始化依赖解析器和可卸载的加载上下文 var resolver = new AssemblyDependencyResolver(webApiAssemblyPath); var loadContext = new AssemblyLoadContext("WebApiControllerLoader", isCollectible: true); // 绑定依赖解析逻辑,自动查找缺失的程序集 loadContext.Resolving += (context, assemblyName) => { var assemblyPath = resolver.ResolveAssemblyToPath(assemblyName); return assemblyPath != null ? context.LoadFromAssemblyPath(assemblyPath) : null; }; try { // 加载WebAPI主程序集 Assembly webApiAssembly = loadContext.LoadFromAssemblyPath(webApiAssemblyPath); // 查找指定命名空间下的控制器类型,增加ControllerBase校验过滤非控制器类 var controllerTypes = webApiAssembly.GetExportedTypes() .Where(t => t.FullName != null && t.FullName.StartsWith("MyTestApp.WebApi.Controllers.") && typeof(ControllerBase).IsAssignableFrom(t)); // 遍历获取所有控制器的公开实例方法 foreach (var controllerType in controllerTypes) { var methodList = controllerType.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly); // 此处处理你需要的方法列表逻辑 } } finally { // 卸载加载上下文,释放资源占用 loadContext.Unload(); }
注意事项
- 如果你的WebAPI使用了单文件发布模式,上述两个方案都无法直接生效,需要调整发布配置关闭单文件发布后再使用。
- 如果需要获取接口的路由、请求方式等信息,可以通过读取方法上的
[HttpGet]/[HttpPost]等特性实现。
内容的提问来源于stack exchange,提问作者Adam Wojnar
相关产品推荐
相关产品推荐

