System.Web.HttpContext.Current.User.Identity.Name Vs System.Environment.UserName in ASP.NET

Description System.Web.HttpContext.Current.User.Identity.Name Gets or sets security information for the current HTTP request. (The Name of the Logged in user on your Website) System.Environment.UserName Gets the user name of the person who is currently logged on to the Windows operating system. More Information MSDN – HttpContext.User Property MSDN – Environment.UserName Property

Why is HttpContext.Current null?

Clearly HttpContext.Current is not null only if you access it in a thread that handles incoming requests. That’s why it works “when i use this code in another class of a page”. It won’t work in the scheduling related class because relevant code is not executed on a valid thread, but a background thread, which … Read more

Setting HttpContext.Current.Session in a unit test

You can “fake it” by creating a new HttpContext like this: http://www.necronet.org/archive/2010/07/28/unit-testing-code-that-uses-httpcontext-current-session.aspx I’ve taken that code and put it on an static helper class like so: public static HttpContext FakeHttpContext() { var httpRequest = new HttpRequest(“”, “http://example.com/”, “”); var stringWriter = new StringWriter(); var httpResponse = new HttpResponse(stringWriter); var httpContext = new HttpContext(httpRequest, httpResponse); var … Read more

Mock HttpContext.Current in Test Init Method

HttpContext.Current returns an instance of System.Web.HttpContext, which does not extend System.Web.HttpContextBase. HttpContextBase was added later to address HttpContext being difficult to mock. The two classes are basically unrelated (HttpContextWrapper is used as an adapter between them). Fortunately, HttpContext itself is fakeable just enough for you do replace the IPrincipal (User) and IIdentity. The following code … Read more