About context

xiaoxiao2021-03-06  111

Susan Warren

Microsoft Corporation

One of the most common problems when writing a web app is to let the code know its execution context. Let us clear this question through a simple example (ie personalized page):

please sign in.

versus

Welcome to Susan!

Although it looks simple, even this small web ui, it still needs several segments, and each time the information will change each time it requests. We need to know the following:

Did the user log in?

What is the user's display name?

What is more common is, what is the only context when each request is requested? And how to write code to take into account this information?

In fact, the web application may need to track many different context segments due to the state of HTTP's stateless features. When the user interacts with the web application, the browser sends a series of independent HTTP requests to the web server. The application itself must organize these request organizations to feel a pleasant experience; at the same time, it is very important to know the context of the request.

The ASP introduces several internal objects such as Request and Application to help track the context of HTTP requests. ASP.NET completes the next step and bundles these objects and several other objects related to the context to form an extremely convenient internal object Context.

Context is an object of System.Web.httpContext (English) type. It is disclosed as an attribute of the ASP.NET Page class. This object can also be obtained by user controls and business objects (described in detail below). The following is some of the list of objects formed by HTTPContext:

Object description

The keyword / value of the Application value is accessed by each user of the application. Application is System.Web.httpApplicationState type.

ApplicationInstance actually runs the application that discloses some request processing events. These events are processed in Global.asax, Httphandler or HttpModule.

Cache ASP.NET Cache objects provide programming access to cache. Rob Howard's ASP.NET CACHING (English) is described in detail.

The first error encountered when Error handles the page (if any). For more information, see Exception to the Rule, Part 1 (English) written by ROB.

The Items keyword / value pair set can be used to pass information between all components involved in processing the same request. Items is System.Collections.IDictionary type.

Request For information about HTTP requests, including browser information, cookies, and values ​​transmitted in a form or query string. Request is System.Web.httpRequest type.

Response is used to create an HTTP response settings and content. Response is the system.web.httpResponse type.

The Server server is a utility class with some useful helper methods, including server.execute (), server.mappath (), and server.htmlencode (). Server is an object of System.Web.httpserverUtility type.

The keyword / value of the Session value can be accessed by a single user of the application. Session is the System.Web.httpSessionState type. TRACE ASP.NET TRACE object provides access to tracking functions. For more information, see the article written by ROB Tracing (English).

User current user (if you have already verified) security context. Context.user.Identity is the name of the user. User is the object of system.security.principle.IPrIncipal type.

If you are an ASP developer, then some objects described above should not feel unfamiliar. Although there are some improvements, it is generally, their roles in ASP.NET are exactly the same in ASP.

Context basic knowledge

Some objects in Context have also been upgraded to top-level objects in Page. For example, page.context.response and page.response refers to the same object, so the following code is equivalent:

[Visual Basic® Web Form]

Response.write ("Hello")

Context.Response.write ("Hello")

[C # web form]

Response.write ("Hello");

Context.Response.write ("Hello");

You can also use the Context object from your business object. HttpContext.current is a static property that can easily return the context of the current request. This is useful in various methods, and there is only a simple example of retrieving items from the business class's cache:

[Visual Basic]

'Get request context

DIM _CONTEXT AS HTTPCONTEXT = httpContext.current

'Getting the data set in the cache

Dim _Data as dataset = _Context.cache ("MyDataSet")

[C #]

// Get the request context

HttpContext _Context = httpContext.current;

/ / Get the data set in the cache

DataSet _Data = _Context.cache ("MyDataSet");

Context in operation

Context object provides answers to some common ASP.NET "how ...?" Issues. Perhaps the best way to illustrate the value of this valuable object is to show it in operation. Here are some of the most clever context techniques I know.

How do I generate an ASP.NET tracking statement from my business class?

Answer: very simple! Use httpcontext.current to get the Context object and call Context.trace.Write ().

[Visual Basic]

Imports system

Imports system.Web

Namespace context

'Demo generate an ASP.NET from the business class

'Tracking statements.

Public class traceemit

Public Sub SomeMethod ()

'Get request context

DIM _CONTEXT AS HTTPCONTEXT = httpContext.current

'Write tracking statements using context

_Context.trace.write ("in Traceemit.SOMEMETHOD))

End Sub

END CLASS

End Namespace [C #]

Using system;

Using system.Web;

Namespace context

{

/ / Demo Generate an ASP.NET from the business class

// Track the statement.

Public class traceemit

{

Public void someMethod () {

// Get the request context

HttpContext _Context = httpContext.current;

// Write tracking statement using the context

_Context.trace.write ("in TRACEEMIT.SOMEMETHOD);

}

}

}

How can I access the session status value from the business class?

Answer: very simple! Use httpcontext.current to get the Context object and then access the context.session.

[Visual Basic]

Imports system

Imports system.Web

Namespace context

'Demo to access the ASP.NET from the business class

'Session.

Public Class Usesession

Public Sub SomeMethod ()

'Get request context

DIM _CONTEXT AS HTTPCONTEXT = httpContext.current

'Access internal session

DIM _Value as object = _Context.Session ("thevalue")

End Sub

END CLASS

End Namespace

[C #]

Using system;

Using system.Web;

Namespace context

{

/ / Demo to access the ASP.NET from the business class

// conversation

Public Class Usesession

{

Public void someMethod () {

// Get the request context

HttpContext _Context = httpContext.current;

// Access internal session

Object _value = _Context.Session ["thevalue"];

}

}

}

How can I add standard headers and footers to each page of the app?

Answer: Handle the application's BeginRequest and endRequest events and use context.response.write to generate the html of the header and footer.

Technically, applications such as BeginRequest can be processed in httpmodule or by using Global.asax. HTTPModules's writing is more difficult, and as shown in this example, the features used by simple applications are usually not used. Therefore, we use the application range of the global.asax file.

As with the ASP page, some inherent ASP.NET contexts have been upgraded to the properties of the HTTPApplication class, where the class represents the Global.asax inheritance class. We don't need to use httpContext.current to get a reference to the Context object; it is available in Global.asax.

In this case, I put the and tags, and a horizontal line into the header portion, and put another horizontal line and the corresponding end marker into the footer portion. The footer also contains copyright news. The result of the operation should be shown below:

Figure 1: Sample of the standard header and footer presentation in the browser

This is a simple example, but you can easily extend it, make it a standard header with navigation, or only output the corresponding statement. Note that if you want the header or footer to contain interactive content, consider using the ASP.NET user control. [Somepage.aspx source code - content example]

General page content

[Visual Basic Global.asax]

<% @ Application Language = "VB"%>