Preventing Thread.CurrentPrincipal from propagatin

2019-05-05 03:08发布

问题:

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



标签: c# .net clr