ASP.NET User Principal assignment to thread.

I’ve been digging into our legacy codebase that does custom identity management and ran into a question I had trouble answering.

Q: Does ASP.NET assign a user to the thread on every request?
A: Yes.

I did a simple demo using the MVC3 template with a fake membership provider.

In Global.asax.cs

private void LogUserState(string method, object sender, EventArgs e)
{
	var application = sender as HttpApplication;
	if (application == null)
		return;

	if (application.User == null || application.User.Identity == null)
		Trace.WriteLine(string.Format("{0}: Current User is Missing. Thread ID {1}", method, Thread.CurrentThread.ManagedThreadId));
	else
		Trace.WriteLine(string.Format("{0}: Current User is {1}. Thread ID {2}", method, application.User.Identity.Name, Thread.CurrentThread.ManagedThreadId));
}

protected void Application_BeginRequest(object sender, EventArgs e)
{
	LogUserState(MethodInfo.GetCurrentMethod().Name, sender, e);
}

protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
	LogUserState(MethodInfo.GetCurrentMethod().Name, sender, e);
}

protected void Application_PostAuthenticateRequest(object sender, EventArgs e)
{
	LogUserState(MethodInfo.GetCurrentMethod().Name, sender, e);
}

Output is as follows

Application_BeginRequest: Current User is Missing. Thread ID 38
Application_AuthenticateRequest: Current User is abc123. Thread ID 38
Application_PostAuthenticateRequest: Current User is abc123. Thread ID 38

Leave a comment