https://docs.microsoft.com/en-us/dotnet/api/system.web.httpcontext?view=netframework-4.8

Encapsulates all HTTP-specific information about an individual HTTP request.

Remarks

Classes that inherit the IHttpModule and IHttpHandler interfaces are provided a reference to an HttpContext object for the current HTTP request.

The object provides access to the intrinsic固有的 Request, Response, and Server properties for the request.

This object is ready for garbage collection when the HttpRequest is completed. Its usage after the request completes could lead to undefined behavior, such as a NullReferenceException.

This object is only available in the thread controlled by ASP.NET. Usage in background threads could lead to undefined behavior.

HttpContext.Request

Gets the HttpRequest object for the current HTTP request.

The Request property provides programmatic access to the properties and methods of the HttpRequest class. Because ASP.NET pages contain a default reference to the System.Web namespace (which contains the HttpContext class), you can reference the members of HttpRequest on an .aspx page without using the fully qualified class reference to HttpContext. For example, you can use Request.Browser to get the capabilities of the client browser. However, if you want to use the members of HttpRequest from an ASP.NET code-behind module, you must include a reference to the System.Web namespace in the module and a fully qualified reference to both the currently active request/response context and the class in System.Web that you want to use. For example, in a code-behind page you must specify the fully qualified name HttpContext.Current.Request.Browser.

Note

ASP.NET will throw an exception if you try to use this property when the HttpRequest object is not available. For example, this would be true in the Application_Start method of the Global.asax file, or in a method that is called from the Application_Start method. At that time no HTTP request has been created yet.

HttpContext.Response

The Response property provides programmatic access to the properties and methods of the HttpResponse class. Because ASP.NET pages contain a default reference to the System.Web namespace (which contains the HttpContext class), you can reference the members of HttpContext on an .aspx page without using the fully qualified class reference to HttpContext.

For example, you can use Response.Write("some output") to write output to an HTTP output stream.

However, if you want to use the members of HttpResponse from an ASP.NET code-behind module, you must include a reference to the System.Web namespace in the module and a fully qualified reference to the currently active request/response context and the class in System.Web that you want to use. For example, in a code-behind page you must specify the fully qualified name HttpContext.Current.Response.Write("some output").

HttpContext Object for Developers

HttpContext object will hold information about the current http request.

In detail, HttpContext object will be constructed newly for every request given to an ASP.Net application and this object will hold current request specific informations like Request, Response, Server, Session, Cache, User and etc.

For every request, a new HttpContext object will be created which the ASP.Net runtime will use during the request processing.

A new HttpContext object will be created at the beginning of a request and destroyed when the request is completed.

To know more about the use of HttpContext object in ASP.Net request processing please follow the article attached in the reference section of this article.

Also, this object can be very well used in our application to solve some of problems which I will discuss in this article.

One of the best features of HttpContext object is using its Item Collection. This article will contemplate on some of the very useful features that can be achieved through HttpContext Class.

Hide QueryString or Pass value with Server.Transfer()

Sometimes, we will have requirements where we need to pass data from source form to destination form when using Server.Transfer() method.

Since, Server.Transfer will make no round trip to the client, the destination page processing will also falls under the same request.

This is one of the ideal scenario where we can use the Item collection of HttpContext object. Refer the below code where we are passing EmployeeID from one form to another.

Source Form

Context.Items.Add("empID", "123456");

Server.Transfer("Destination.aspx");

Destination Form

string empID = Context.Items["empID"].ToString();

Response.Write(empID);

Accessing Request/Response/Server/Session/Cache/User object in a Class

Most of us think the above objects can be accessed only in CodeBehind file and it can’t be accessed outside codebehind class i.e. any other custom class. But in reality, it can be accessed via the current request’s HttpContext object.

How to get the HttpContext object of the current request in a class file?

HttpContext class has a static property called Current which gives us the reference of current request’s HttpContext object. Once we have the HttpContext object we can access those objects easily.

public class AccessPageObjects

{

       public AccessPageObjects()

       {

              //

              // TODO: Add constructor logic here

              //

       }

    public void Print()

    {

        HttpContext context = HttpContext.Current;

        context.Response.Write("Test");

        context.Session["Key"] = "Value";

        string user = context.User.Identity.Name;     

    }

}

For the above code to work we need to make sure that we are including System.Web namespace in the class file.

Pass value to usercontrols using HttpContext object

We can pass values to usercontrols from codebehind using Context.Item Collection.

UserControl

public partial class WebUserControl : System.Web.UI.UserControl

{

protected void Page_Load(object sender, EventArgs e)

{

Employee emp = Context.Items["emp"] as Employee;

Response.Write(emp.FirstName + " " + emp.LastName + " in user control.");

}

}

The above requirement can also be achieved through Page.Item collections in the same way like above. But Context object will be really useful when we need to pass an object from a source page to destination page’s usercontrols.

Source Form

Employee emp = new Employee();

emp.FirstName = "Satheesh";

emp.LastName = "Babu";

Context.Items.Add("emp", emp);

Server.Transfer("Destination.aspx");

UserControl in Destination Page

public partial class WebUserControl : System.Web.UI.UserControl

{

protected void Page_Load(object sender, EventArgs e)

{

Employee emp = Context.Items["emp"] as Employee;

Response.Write(emp.FirstName + " " + emp.LastName + " in user control.");

}

}

ASP.Net Request Processing Time

A very good use of HttpContext object will be calculating the request processing time. Take a look at Rick’s article in West-Wind with the title “A low-level Look at the ASP.NET Architecture” where he explains it very neatly. Find the link in the reference section for a depth understanding in ASP.Net request processing. Request processing time can be calculated in Global.asax file through Application_BeginRequest and Application_EndRequest event. By default, this event will not be present in Global.asax file so we need to add it explicitly.

protected void Application_BeginRequest(Object sender, EventArgs e)

{

Context.Items.Add("Request_Start_Time", DateTime.Now);

}

protected void Application_EndRequest(Object sender, EventArgs e)

{

TimeSpan tsDuration = DateTime.Now.Subtract((DateTime)Context.Items["Request_Start_Time"]);

}

Conclusion

This article will help developers to understand the usage of HttpContext object at one place to achieve some of the handy things. Most of the tips discussed here use Item collection in the Context object to accomplish the tasks and this proves the importance of Item collection packed with HttpContext object. Thus, we can understand that HttpContext object is not only used by the ASP.Net runtime for request processing but also by developers.

Happy Coding!!

What is httpcontext的更多相关文章

  1. 异步 HttpContext.Current 为空null 另一种解决方法

    1.场景 在导入通讯录过程中,把导入的失败.成功的号码数进行统计,然后保存到session中,客户端通过轮询显示状态. 在实现过程中,使用的async调用方法,出现HttpContext.Curren ...

  2. 解决Asp.net Mvc中使用异步的时候HttpContext.Current为null的方法

    在项目中使用异步(async await)的时候发现一个现象,HttpContext.Current为null,导致一系列的问题. 上网查了一些资料后找到了一个对象: System.Threading ...

  3. HttpContext.Cache属性

    HttpContext基于HttpApplication的处理管道,由于HttpContext对象贯穿整个处理过程,所以,可以从HttpApplication处理管道的前端将状态数据传递到管道的后端, ...

  4. System.Web.HttpContext.Current.Session为NULL解决方法

    http://www.cnblogs.com/tianguook/archive/2010/09/27/1836988.html 自定义 HTTP 处理程序,从IHttpHandler继承,在写Sys ...

  5. Session 、Application 和 HttpContext 的使用区别

    在ASP.NET WEB页面开发中,经常会需要保存一些信息,以便在不同的页面或时间段都能够访问到.这其中便会用到Session和Application. Session .Application 和 ...

  6. Why is HttpContext.Current null after await?

    今天在对项目代码进行异步化改进的时候,遇到一个奇怪的问题(莫笑,以前没遇过),正如标题一样,HttpContext.Current 在 await 异步执行之后,就会变为 null. 演示代码: pu ...

  7. 在ASP.NET Core中怎么使用HttpContext.Current

    一.前言 我们都知道,ASP.NET Core作为最新的框架,在MVC5和ASP.NET WebForm的基础上做了大量的重构.如果我们想使用以前版本中的HttpContext.Current的话,目 ...

  8. HttpContext.Current.Session.SessionID相关问题及备忘

    今天Tony提到说我们系统中会利用如下代码来判断用户是否过期. if (string.IsNullOrEmpty(UserContext.ConnectionSessionId)) { LogUIFa ...

  9. 【C#】关于HttpContext.Current.Request.QueryString 你要知道点

    HttpContext.Current.Request.QueryString[ ]括号中是获取另一个页面传过的的参数值 HttpContext.Current.Request.Form[“ID”]· ...

  10. Asp.Net HttpContext.RemapHandler 用法

    最近在看HttpHandler映射过程文章时发现Context对象中有一个RemapHandler方法,它能将当前请求映射到指定的HttpHandler处理,可跳过系统默认的Httphandler.它 ...

随机推荐

  1. chapter2

    Chapter2 Tip1 静态工厂方法代替构造器 公有的静态方法,只是一个返回类实例的静态方法. 静态工厂方法的优势: 优势一: 有名称,如果构造器本身没有正确的描述被返回的对象,具有适当名称的静态 ...

  2. C# 数据类型之间的转换

    C数据类型转换 https://www.cnblogs.com/bluestorm/p/3168719.html 1 字符串解析为整数: a = int.Parse (Console.ReadLine ...

  3. Javascript之谈对象

    谈谈如何理解对象 使用预定义对象只是面向对象语言的能力的一部分,ECMAScript 真正强大之处在于能够创建自己专用的类和对象.面向对象的语言有一个标志,那就是它们都有类的概念,而通过类可以创建任意 ...

  4. UVA-10462.Is There A Second Way Left(Kruskal+次小生成树)

    题目链接 本题大意:这道题用Kruskal较为容易 参考代码: #include <cstdio> #include <cstring> #include <vector ...

  5. Java学习day5程序控制流程二

    循环结构: 循环语句的四个组成部分:1.初始化部分(init_statement) 2.循环条件部分(test_exp) 3.循环体部分(body_statement) 4.迭代部分(after_st ...

  6. Codeforces 916E(思维+dfs序+线段树+LCA)

    题面 传送门 题目大意:给定初始根节点为1的树,有3种操作 1.把根节点更换为r 2.将包含u,v的节点的最小子树(即lca(u,v)的子树)所有节点的值+x 3.查询v及其子树的值之和 分析 看到批 ...

  7. Python2中range 和xrange的区别??

    两者用法相同,不同的是range返回的结果是一个列表,而xrange的结果是一个生成器, 前者是直接开辟一块内存空间来保存列表,后者是边循环边使用,只有使用时才会开辟内存空间, 所以当列表很长时,使用 ...

  8. HDU 4285 circuits( 插头dp , k回路 )

    circuits Time Limit: 30000/15000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total ...

  9. Keyboarding (bfs+预处理+判重优化)

    # #10030. 「一本通 1.4 练习 2」Keyboarding [题目描述] 给定一个 $r$ 行 $c$ 列的在电视上的"虚拟键盘",通过「上,下,左,右,选择」共 $5 ...

  10. java实战应用:MyBatis实现单表的增删改

    MyBatis 是支持普通 SQL查询.存储过程和高级映射的优秀持久层框架.MyBatis 消除了差点儿全部的JDBC代码和參数的手工设置以及结果集的检索.MyBatis 使用简单的 XML或注解用于 ...