Preventing Thread.CurrentPrincipal from propagating across application domains

对着背影说爱祢 提交于 2019-12-07 07:51:38

问题


Does anyone if it's possible to stop the current thread's IPrincipal from propagating over an application domain boundary? I have no control over the IPrincipal that's assigned to the thread, but I do have control over creating the application domains.

(The reason I want to do this is to prevent a serialization error from occuring if the principal object type's assembly is unavailable in the other domain.)

Edit: ExecutionContext.SuppressFlow looks promising, but it doesn't appear to achieve the goal. The following prints "MyIdentity":

static void Main ()
{
    ExecutionContext.SuppressFlow ();
    Thread.CurrentPrincipal = new GenericPrincipal (new GenericIdentity ("MyIdentity"), "Role".Split ());
    AppDomain.CreateDomain ("New domain").DoCallBack (Isolated);
}

static void Isolated ()
{
    Console.WriteLine ("Current principal: " + Thread.CurrentPrincipal.Identity.Name);  // MyIdentity
}

回答1:


You didn't run an asynchronous method, the target function is executed in the secondary appdomain by the same thread. So the principal doesn't change. This works:

        var flow = ExecutionContext.SuppressFlow();
        Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity("MyIdentity"), "Role".Split());
        ThreadPool.QueueUserWorkItem((x) => {
            AppDomain.CreateDomain("New domain").DoCallBack(Isolated);
        });
        flow.Undo();

Or if you just want to run the same thread with a specific context then you can use ExecutionContext.Run():

        var copy = ExecutionContext.Capture();
        Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity("MyIdentity"), "Role".Split());
        ExecutionContext.Run(copy, new ContextCallback((x) => {
            AppDomain.CreateDomain("New domain").DoCallBack(Isolated);
        }), null);



回答2:


This appears to do what you want:

System.Threading.ExecutionContext

Specifically, take a look at the SuppressFlow method.

Chris



来源:https://stackoverflow.com/questions/11489673/preventing-thread-currentprincipal-from-propagating-across-application-domains

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!