Difference between HttpContext.Current and Controller.Context in MVC ASP.NET

asp.net Mvc

asp.net Mvc Problem Overview


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?

asp.net Mvc Solutions


Solution 1 - asp.net Mvc

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

Solution 2 - asp.net Mvc

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTonEView Question on Stackoverflow
Solution 1 - asp.net MvcLuceroView Answer on Stackoverflow
Solution 2 - asp.net MvcLeviView Answer on Stackoverflow