74

I am working on an MVC ASP .NET application. I am relatively new to both.

In a controller I am trying to get the current log on user, for which there seem to be two ways of doing this:

System.Web.HttpContext.Current.User.Identity.Name

Or

HttpContext.User.Identity.Name

What is the difference between these? As far as a I can tell within the MVC framework the controller has the current HttpContext stored as a property so these methods are identical. Is that correct?

GEOCHET
  • 21,119
  • 15
  • 74
  • 98
TonE
  • 2,975
  • 5
  • 30
  • 50

2 Answers2

93

Yes, they will usually be identical. However, if you're working with additional threads, they will not be; System.Web.HttpContext.Current is threadstatic.

Lucero
  • 59,176
  • 9
  • 122
  • 152
  • 39
    Just to clarify your otherwise excellent answer: ThreadStatic means that the value is tied to the thread. That is, in any additional thread, you cannot access HttpContext.Current. – Tamas Czinege Apr 24 '09 at 11:42
  • 6
    Also, don't forget that there is a ControllerContext as well on the controller that includes MVC specific information like the RouteData collection. – James Avery Apr 24 '09 at 12:03
27

The context provided by the controller (not the static HttpContext.Current) is mockable. If you're interested in unit-testing your code, it's generally far easier to create a mock ControllerContext and set it on the Controller than it is to go through HttpContext.Current. Otherwise ControllerContext.HttpContext points to the same data as HttpContext.Current.

Levi
  • 32,628
  • 3
  • 87
  • 88