Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between HttpContext.Current.User and Thread.CurrentPrincipal in asp.net?

Well, I think the title is clear enough.

like image 565
Lieven Cardoen Avatar asked Dec 03 '09 22:12

Lieven Cardoen


2 Answers

The biggest difference is that they do not have to be the same.

Generally speaking, HttpContext.Current.User is the logon user (when it is called on a worker thread) while Thread.CurrentPrincipal is the worker process identity.

On IIS 5.x, Thread.CurrentPrincipal by default is ASPNET. On IIS 6 and above, Thread.CurrentPrincipal by default is Network Service (or the application pool identity you change to).

To make it complex, if you enable ASP.NET impersonation, then both of them might be the same as the logon user.

Try to read some really good books on this topic and Microsoft MSDN articles,

http://msdn.microsoft.com/en-us/library/ms998351.aspx

Another suggestion is to use a debugger to attach to the worker process and check those at runtime. That can give you a better look.

Note that HttpContext.Current.User is not the best way to query logon user identity. You should stick to Page.User for WebForms, and Controller.User for MVC, and ApiController.User for Web API.

like image 106
Lex Li Avatar answered Oct 26 '22 14:10

Lex Li


Another big difference is that your code doesn't always have access to the HttpContext. (For example if you have all of your BL in an assembly that may or may not be used from a web application) While they two user accounts can be different, if you use the Thread.CurrentPrincipal then your code will always be able to get at that user object no matter where you are in your code.

like image 34
Arthur C Avatar answered Oct 26 '22 14:10

Arthur C