What is the difference between HttpContext.Current.User and HttpContext.User

I am currently working with some legacy code that uses the HttpContext.Current.User property in the MVC controller method to perform some basic authorization for the current user. From reading the documentation, there is also the HttpContext.User property, and both of them seem to indicate that they can get / set the current user. I am curious if at some levels they are interchangeable and the same, or if there is a key difference between 2 that will cause unintended problems in terms of authorization or even recognition of the current user of the web application.

+5
source share
3 answers

the documentation explains this (highlighting added, and although this applies to web forms, I find the principle is similar in MVC)

Because ASP.NET pages contain the default link for the System.Web namespace (which contains the HttpContext class), you can reference HttpContext members on the .aspx page without using the full reference to the HttpContext class. For example, you can use User.Identity.Name to get the name of the user on whose behalf the current process is running.

However, if you want to use IPrincipal members from a code module with ASP.NET code, you must include a reference to the System.Web namespace in the module and a fully qualified reference to both the current active request / response context and the class in System.Web that you want to use

For example, on the code page, you must specify the full name HttpContext.Current.User.Identity.Name.

+1
source

Both HttpContext.Current and HttpContext are the same as the return httpContext object for the current HTTP request.
But later is a property of the controller object, so it is available ONLY in the controller.

+1
source

You cannot directly refer to HttpContext.User , except possibly inside the controller. User is a property of the HttpContext class. You can do something like this:

 HttpContext context = HttpContext.Current; IPrincipal user = context.User; 

that is, you can refer to a property through an instance of the HttpContext class.

The base class of the Controller has a property called HttpContext . Inside the controller, if you reference HttpContext.User , you refer to base.HttpContext.User , which usually (always?) Will be the same as HttpContext.Current.User , simply because base.HttpContext will be at all (maybe always ?) Be the same as HttpContext.Current .

0
source

Source: https://habr.com/ru/post/1207177/


All Articles