asp.net - 如何在 .Net 5 中加载为另一个 .net 版本构建的 .dll?

标签 asp.net asp.net-mvc asp.net-core

在以前版本的 ASP.NET(直到版本 4.6)中,我们可以通过修改 web.config 来加载为另一个 .net 版本构建的 *.dll,如下所示:

<configuration>
     <startup useLegacyV2RuntimeActivationPolicy="true" >   
     </startup>
</configuration>

但在 ASP.NET 5 中,没有 web.config,而是完全不同的配置系统。那么如何才能在新版本中获得相同的结果呢?

最佳答案

这篇博文展示了如何在运行时设置此策略(相对于“设计时” - 通过编辑 web.config)http://reedcopsey.com/2011/09/15/setting-uselegacyv2runtimeactivationpolicy-at-runtime/但我自己还没有尝试过 ASP.NET 5。但也适用于早期版本。

基本上,您创建了这个静态帮助器类

public static class RuntimePolicyHelper
{
    public static bool LegacyV2RuntimeEnabledSuccessfully { get; private set; }

    static RuntimePolicyHelper()
    {
        ICLRRuntimeInfo clrRuntimeInfo =
            (ICLRRuntimeInfo)RuntimeEnvironment.GetRuntimeInterfaceAsObject(
                Guid.Empty, 
                typeof(ICLRRuntimeInfo).GUID);
        try
        {
            clrRuntimeInfo.BindAsLegacyV2Runtime();
            LegacyV2RuntimeEnabledSuccessfully = true;
        }
        catch (COMException)
        {
            // This occurs with an HRESULT meaning 
            // "A different runtime was already bound to the legacy CLR version 2 activation policy."
            LegacyV2RuntimeEnabledSuccessfully = false;
        }
    }

    [ComImport]
    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    [Guid("BD39D1D2-BA2F-486A-89B0-B4B0CB466891")]
    private interface ICLRRuntimeInfo
    {
        void xGetVersionString();
        void xGetRuntimeDirectory();
        void xIsLoaded();
        void xIsLoadable();
        void xLoadErrorString();
        void xLoadLibrary();
        void xGetProcAddress();
        void xGetInterface();
        void xSetDefaultStartupFlags();
        void xGetDefaultStartupFlags();

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        void BindAsLegacyV2Runtime();
    }
}

用法:

// before calling the code from your legacy assembly - 
if (RuntimePolicyHelper.LegacyV2RuntimeEnabledSuccessfully)
{
    // your Legacy code
}

关于asp.net - 如何在 .Net 5 中加载为另一个 .net 版本构建的 .dll?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34284439/

相关文章:

c# - 程序集使用版本 X,其版本高于引用的程序集错误

ASP.NET 避免在页面刷新时添加新数据

asp.net - SQL Server Reporting Services - 运行报告时出错(Azure 网站部署问题?)

c# - 如何正确获取Json值?

jquery - 使用 jqGrid 用户数据

c# - 在 ASP.NET Core Identity UI 中更改路由?

c# - 在 ASP.NET Core 中间件构造函数中混合依赖注入(inject)和手动传递参数

c# - 编译器错误消息 : CS0246: when I renamed my project

asp.net - 如何更改asp悬停时的背景图像:CommandField in a Gridview

jquery - 在 ASP.NET 中使用 ASP.NET MVC 验证