ASP.NET : Stick to the Context
What we are talking about?
We are talking about HttpContext Class. It is a part of System.Web namespace/assembly and is usually referred by,
What is its significance?
We know that HTTP has a stateless nature.When a user requests for a web application, the browser sends many independent requests to the server for the resources. ASP.NET has to maintain information about the the current HTTP request,running application, user session and many more processes, and finally blend them together to provide a personal experience to the user.
How a seamless experience is achieved?
To build a context, we require few classes which we are already using to maintain the state of the application. Then, All this context-related objects are blend into an extremely handy intrinsic object called Context.
Few of the objects are,
Application: A key/value pair collection of values that provides access to application-wide methods and events for all sessions..
Cache: The ASP.NET Cache object, which provides programmatic access to the cache.
Items: A key-value pair collection to store information and can be used to pass information between components.For example, the same piece of information can be used in Global.asax, in ASPX page, in the user controls within the page, and by the business logic the page calls.Context.Items as a state mechanism for very short-lived values.
Request: Information about the HTTP request, including browser information, cookies, request headers, cookies, client certificate, query string and many more.
Response: Provides access to the output stream for the current page. It is regularly required to write the cookie information.
Server: Exposes several useful helper methods, including Server.Execute(),Server.MapPath(), and Server.HtmlEncode(). This object is mainly used to transfer control between pages.
Session: A key/value pair collection of values that provides information to the current user session of the application.
User: The security context of the current user, if authenticated. Context.User.Identity is the user’s name.
Note-HttpContext.Current is a static property that is used to deliver the context for the current request.
// current context HttpContext _context = HttpContext.Current; // retrieve Session value object _value = _context.Session["Key"];
We have now two ways to access Request object.
HttpContext.Current.Request and Request directly from the base class.
Best part is they both behave the same way, but the optimal performance is provided by Direct Request object as there is no overhead of calling HttpContext object.