简体   繁体   中英

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

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.

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.

这是一种访问当前HttpContext的方法,该HttpContext可能没有对上下文的引用,但是在活动的Web请求中。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM