One of the most important classes in the pipeline is the HttpContext class. This class maintains all the request-specific data and is accessible to most elements within the pipeline. The context class shows up as a parameter to many methods , including the ProcessRequest method of handlers, and it is directly accessible via the Context property of both the Page class and the HttpApplication class. Table 4-1 shows the set of properties available on the HttpContext class. Table 4-1. Properties of HttpContext
The Items property bag is a particularly useful collection to be aware of because it lets you store and retrieve request-specific data from anywhere in the pipeline. This can be useful if you are building custom modules, for example, and want to save information at one point during the request to read again later in the request. The interface to the Items collection is similar to all the other property-bag collections, using a string-based indexer to store an object reference. Another useful property to know about is the static Current property of the HttpContext class. This property always points to the current instance of the HttpContext class for the request being serviced. This can be convenient if you are writing helper classes that will be used from pages or other pipeline classes and may need to access the context for whatever reason. By using the static Current property to retrieve the context, you can avoid passing a reference to it to helper classes. For example, the class shown in Listing 4-1 uses the Current property of the context to access the QueryString and print something to the current response buffer. Note that for this static property to be correctly initialized , the caller must be executing on the original request thread, so if you have spawned additional threads to perform work during a request, you must take care to provide access to the context class yourself. Listing 4-1 Using the Current Property of HttpContextpublic class MyClass { void SomeFunction() { HttpContext ctx = HttpContext.Current; ctx.Response.Write("Hello, "); string name = ctx.Request.QueryString["name"]; ctx.Response.Output.WriteLine(name); } } |