Masoud Darvishian
Masoud Darvishian

Reputation: 3964

why do we use HttpContext.Current?

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;
    }
}

Upvotes: 11

Views: 33823

Answers (4)

Don Feto
Don Feto

Reputation: 1486

before asp.net MVC in a web form, there were classes request, response where you can get cookies and session and those staff in MVC all the HTTP information like request and response and their properties are now inside HTTpcontext.

Upvotes: 0

Erik Funkenbusch
Erik Funkenbusch

Reputation: 93424

That's like saying "Why do I need to go to a bank to get money?", to which the answer is "Because that's where the money is.

To answer your question. Because that's where the Session is. It's really that simple. You don't have to know why, just that that's where it is.

There's a much longer explanation, which other people are giving with all the technical details. But in the end, the answer just boils down to this.

Upvotes: 4

Oybek
Oybek

Reputation: 7243

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.

Upvotes: 31

Darren Kopp
Darren Kopp

Reputation: 77627

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.

Upvotes: 4

Related Questions