tags:

views:

1001

answers:

2

How do you clear the thread principal in c#.

I have a background thread that does a

Membership.ValidateUser(username, password);

which then copies the resulting Principal back to the main thread

AppDomain.CurrentDomain.SetThreadPrincipal(Thread.CurrentPrincipal);

this works fine. But, if I log off I want to clear the principal, if I set it to null it does nothing Thread.CurrentPrincipal = null; if I try and set it again via

AppDomain.CurrentDomain.SetThreadPrincipal(Thread.CurrentPrincipal);

I get the error

Default principal object cannot be set twice.

Any ideas?

+2  A: 

I don't think you can reset the principal without shutting down the AppDomain and recreating it. You only get one shot at calling SetThreadPrincipal.

Assuming that you are using your own custom principal object that you create after ValidateUser; you can probably put a "Logout" method on your principal that resets its internal state to an unauthenticated user.

DancesWithBamboo
That could well be the case. I have no problem if I call membership.validateuser on the dispatcher thread a few times, it always just writes another principal in. Maybe I'm trying to update the wrong principal. Any idea what principal the validateUser updates?
yes, you only get one call to the SetThreadPrincipal method
TheZenker
+1  A: 

If you only want to set the principal for your main thread pass a reference along to background thread and then set the principal using the CurrentPrincipal property.

e.g. mainThead.CurrentPrincipal=Thread.CurrentPrincipal.

When you are finished set it to the original principal

chris