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
}
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);
This appears to do what you want:
System.Threading.ExecutionContext
Specifically, take a look at the SuppressFlow method.
Chris
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.