C# IIS发布时发生程序集加载错误的原因

C# IIS发布时发生程序集加载错误的原因,c#,.net,asp.net-core,system.reflection,C#,.net,Asp.net Core,System.reflection,我创建了一个扩展方法,用于在asp.net核心web api项目中查找接口实现 public static List<Type> FromAssembliesMatching<TType>(this AppDomain currentDomain, string searchPattern) { var referencedPaths = Directory.GetFiles(currentDomain.BaseDirectory, "*.

我创建了一个扩展方法,用于在asp.net核心web api项目中查找接口实现

    public static List<Type> FromAssembliesMatching<TType>(this AppDomain currentDomain, string searchPattern)
    {
        var referencedPaths = Directory.GetFiles(currentDomain.BaseDirectory, "*.dll").ToList();

        var assemblies = referencedPaths.Select(path => currentDomain.Load(AssemblyName.GetAssemblyName(path)));

        var types = assemblies.SelectMany(s => s.GetTypes().Where(t =>
                typeof(TType).IsAssignableFrom(t)
                && !t.IsInterface
                && !t.IsAbstract))
            .ToList();

        return types;
    }
扩展方法尝试加载所有DLL。我认为c#生成的DLL会导致错误。如何解决这个问题?

这是意料之中的

由于您使用的部署方法(自包含),
dotnet publish不仅复制所有托管程序集,还复制本机依赖项,如
api-ms-win-core-console-l1-1-0.dll
。这些本机依赖项无法通过反射加载到应用程序域,因此异常是完全正常的

不过,您有几个选项可以解决此问题

  • 捕获异常并忽略它
  • 或者主动检查dll是本机的还是通过使用进行管理的
  • 这是意料之中的事

    由于您使用的部署方法(自包含),
    dotnet publish不仅复制所有托管程序集,还复制本机依赖项,如
    api-ms-win-core-console-l1-1-0.dll
    。这些本机依赖项无法通过反射加载到应用程序域,因此异常是完全正常的

    不过,您有几个选项可以解决此问题

    • 捕获异常并忽略它
    • 或者主动检查dll是本机的还是通过使用进行管理的
    System.BadImageFormatException: Could not load file or assembly 'C:\publish\api-ms-win-core-console-l1-1-0.dll'.