使用包含自定义IIdentity的主体设置Thread.CurrentPrincipal时的ModuleLoadException

时间:2012-09-05 13:47:49

标签: c++ asp.net asp.net-mvc com asp.net-web-api

我们在ASP.NET MVC WebAPI中托管了一个应用程序,它使用外部托管库。此托管库再次使用COM库。 COM库是许多应用程序和不同版本使用的通用库,因此我们希望能够通过直接从bin文件夹加载来并行运行它,而不是使用传统的COM注册。我们通过添加清单文件并在kernel32.dll中调用CreateActCtx来注册自定义激活上下文(代码包含在下面)来实现这一点。

这本身工作正常,但是当我们在加载COM库之前将Thread.CurrentPrincipal设置为带有自定义IIdentity实现的GenericPrincipal实例时,我们得到一个< CrtImplementationDetails> .ModuleLoadException,并显示消息“C ++模块失败在尝试初始化默认appdomain时加载。“它有一个内部System.Runtime.Serialization.SerializationException,它说它无法加载实际上首先启动COM程序集加载的程序集。堆栈跟踪是:

Server stack trace: 
    at System.Runtime.Serialization.Formatters.Binary.BinaryAssemblyInfo.GetAssembly()
    at System.Runtime.Serialization.Formatters.Binary.ObjectReader.GetType(BinaryAssemblyInfo assemblyInfo, String name)
    at System.Runtime.Serialization.Formatters.Binary.ObjectMap..ctor(String objectName, String[] memberNames, BinaryTypeEnum[] binaryTypeEnumA, Object[] typeInformationA, Int32[] memberAssemIds, ObjectReader objectReader, Int32 objectId, BinaryAssemblyInfo assemblyInfo, SizedArray assemIdToAssemblyTable)
    at System.Runtime.Serialization.Formatters.Binary.__BinaryParser.ReadObjectWithMapTyped(BinaryObjectWithMapTyped record)
    at System.Runtime.Serialization.Formatters.Binary.__BinaryParser.Run()
    at System.Runtime.Serialization.Formatters.Binary.ObjectReader.Deserialize(HeaderHandler handler, __BinaryParser serParser, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage)
    at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream, HeaderHandler handler, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage)
    at System.Runtime.Remoting.Channels.CrossAppDomainSerializer.DeserializeObject(MemoryStream stm)
    at System.Runtime.Remoting.Messaging.SmuggledMethodCallMessage.FixupForNewAppDomain()
    at System.Runtime.Remoting.Channels.CrossAppDomainSink.DoDispatch(Byte[] reqStmBuff, SmuggledMethodCallMessage smuggledMcm, SmuggledMethodReturnMessage& smuggledMrm)
    at System.Runtime.Remoting.Channels.CrossAppDomainSink.DoTransitionDispatchCallback(Object[] args)

Exception rethrown at [0]: 
    at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
    at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
    at System.AppDomain.get_Id()
    at <CrtImplementationDetails>.DoCallBackInDefaultDomain(IntPtr function, Void* cookie)
    at <CrtImplementationDetails>.LanguageSupport._Initialize(LanguageSupport* )
    at <CrtImplementationDetails>.LanguageSupport.Initialize(LanguageSupport* )
    --- End of inner exception stack trace ---
    at <CrtImplementationDetails>.LanguageSupport.Initialize(LanguageSupport* )
    at .cctor()
    --- End of inner exception stack trace ---

当我们没有设置Thread.CurrentPrincipal或使用带有GenericIdentity的GenericPrincipal时,它可以正常工作。目前,使用GenericIdentity的解决方案是我们的解决方法,因为我们主要设置Thread.CurrentPrincipal以使用ASP.NET MVC身份验证。

以下代码有效:

Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity("bla"), new string[0]);

......而以下情况并非如此:

Thread.CurrentPrincipal = new GenericPrincipal(new CustomIdentity("bla"), new string[0]);

以下是global.asax代码,用于注册引用bin文件夹和清单文件的自定义激活上下文,以执行无注册COM:

public class Global : System.Web.HttpApplication
{
    private const UInt32 ERROR_SXS_PROCESS_DEFAULT_ALREADY_SET = 14011;
    IntPtr hActCtx;
    private static readonly ILogger s_logger = LogManager.GetCurrentClassLogger();

    protected void Application_Start(object sender, EventArgs e)
    {
        // Required files are copied in host projects post-build event
        // NB! you can only set the default activation context like this once per app domain,
        //  so if you need multiple apps/services using side-by-side they cannot share app pool.

        UInt32 dwError = 0;
        string binDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"bin");
        string manifestPath = Path.Combine(binDirectory, "Iit.OpenApi.Services.ReferenceData.manifest");
        var activationContext = new ACTCTX();
        activationContext.cbSize = Marshal.SizeOf(typeof(ACTCTX));
        activationContext.dwFlags = ACTCTX_FLAG_SET_PROCESS_DEFAULT | ACTCTX_FLAG_ASSEMBLY_DIRECTORY_VALID;
        activationContext.lpSource = manifestPath;
        activationContext.lpAssemblyDirectory = binDirectory;
        hActCtx = CreateActCtx(ref activationContext);
        if (hActCtx.ToInt32() == -1)
        {
            dwError = (UInt32)Marshal.GetLastWin32Error();
        }

        if ((hActCtx.ToInt32() == -1) && (dwError != Global.ERROR_SXS_PROCESS_DEFAULT_ALREADY_SET))
        {
            var err = string.Format("Cannot create process-default win32 sxs context, error={0} manifest={1}", dwError, manifestPath);
            throw new ApplicationException(err);
        }
        // TODO: add eventid to enum
        if ((hActCtx.ToInt32() == -1) && (dwError == Global.ERROR_SXS_PROCESS_DEFAULT_ALREADY_SET))
        {
            GetCurrentActCtx(out hActCtx);
            s_logger.Info(9998, string.Format("Re-using exising ActivationContext [{0}].", hActCtx.ToInt64()));
        }
        else
        {
            s_logger.Info(9998, string.Format("ActivationContext [{0}] created successfully.", hActCtx.ToInt64()));
        }

    }

    protected void Application_End()
    {
        if (hActCtx.ToInt64() != INVALID_HANDLE_VALUE)
        {
            ReleaseActCtx(hActCtx);
            // TODO: add eventid to enum
            s_logger.Info(9999, string.Format("ActivationContext [{0}] released successfully.", hActCtx.ToInt64()));
        }
    }

    [StructLayout(LayoutKind.Sequential)]
    private struct ACTCTX
    {
        public int cbSize;
        public uint dwFlags;
        public string lpSource;
        public ushort wProcessorArchitecture;
        public ushort wLangId;
        public string lpAssemblyDirectory;
        public string lpResourceName;
        public string lpApplicationName;
    }

    private const uint ACTCTX_FLAG_ASSEMBLY_DIRECTORY_VALID = 0x004;
    private const uint ACTCTX_FLAG_SET_PROCESS_DEFAULT = 0x010;
    private const Int64 INVALID_HANDLE_VALUE = -1;

    [DllImport("kernel32.dll", SetLastError = true)]
    private static extern IntPtr CreateActCtx(ref ACTCTX actctx);

    [DllImport("kernel32.dll", SetLastError = true)]
    private static extern bool GetCurrentActCtx(out IntPtr hActCtx);

    [DllImport("kernel32.dll", SetLastError = true)]
    private static extern void ReleaseActCtx(IntPtr hActCtx);

}

使用自定义IIdentity时出现问题的任何输入,以及如何使用reg-free COM工作?

0 个答案:

没有答案