Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why do we use HttpContext.Current?

Tags:

c#

asp.net

I don't know, why do we use HttpContext.Current?
In this property I use it for Session but I don't know why!

public static string Name
{
    get
    {
         if (HttpContext.Current.Session["_n_"] != null)
            return HttpContext.Current.Session["_n_"].ToString();
         else return "";
    }
    set
    {
         HttpContext.Current.Session["_n_"] = value;
    }
}
like image 457
Masoud Darvishian Avatar asked May 23 '12 05:05

Masoud Darvishian


People also ask

What can I use instead of HttpContext current?

Instead of using HttpContext. Current , use the HttpContext provided as a property on the Page or Controller , or even better, you can simply use the Session property.

What is HttpContext current in C#?

This property is a static property of the HttpContext class. The property stores the HttpContext instance that applies to the current request. The properties of this instance are the non-static properties of the HttpContext class. You can also use the Page.

Why HttpContext current is null?

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".

What is HttpContext HTTP request and Httpresponse?

HttpRequest is a subset of HttpContext . In other words, the HttpContext includes the response, the request, and various other data that's not relevant to a specific request or response; such as the web application, cached data, server settings and variables, session state, the authenticated user, etc.


2 Answers

HttpContext is an object that wraps all http related information into one place. HttpContext.Current is a context that has been created during the active request. Here is the list of some data that you can obtain from it.

  1. Request type (Post, Get)
  2. Request parameters (querystring, posted data)
  3. User's IP address
  4. Cookies

Further you can control your output through this object. In Items property, which is a dictionary, you can store instances of objects to ensure that they are created once for the request. You can control the output stream applying your custom filters.

This is a short list of that what you can do with this property.

like image 148
Oybek Avatar answered Nov 02 '22 04:11

Oybek


It's a way to get access to the current HttpContext someplace that may not have a reference to the context but is within an active web request.

like image 32
Darren Kopp Avatar answered Nov 02 '22 06:11

Darren Kopp