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
Font>
[Visual Basic Global.asax]
<% @ Application Language = "VB"%>
Sub Application_BeginRequest (Sender As Object, E AS Eventargs)
'Generate header
Context.Response.write ("" controlchars.lf _ _
"
" controlchars.lf "End Sub
Sub Application_ENDREQUEST (Sender As Object, E AS Eventargs)
'Generate footer
Context.response.write ("
"2002 Microsoft Corporation Copyright" _
ControlChars.lf " body>" controlchars.lf " html>")
End Sub
script>
[C # global.asax]
<% @ Application Language = "C #"%>
Void Application_BeginRequest (Object Sender, Eventargs E) {
/ / Generate header
Context.response.write (" / n
/ n}
Void Application_ENDREQUEST (Object Sender, Eventargs E) {
// Generate footer
Context.Response.write ("
Context.Response.write (" body> / n html>");
}
script>
How to display welcome information after authentication?
Answer: Test the User context object to see if the user is authenticated. If so, you have to get the username from the User object. Of course, this is an example of the beginning of this article.
[Visual Basic]
SUB Page_Load (Sender As Object, e as eventargs) {if user.Identity.isauthenticated THEN
Welcome.text = "Welcome" User.Identity.Name
Else
'Is not logged in, add a link to the login page
Welcome.text = "Please login!"
Welcome.navigateURL = "Signin.aspx"
END IF
End Sub
script>
asp: hyperlink>
[C #]
Void Page_Load (Object Sender, Eventargs E) {
User.Identity.isauthenticated) {
Welcome.text = "Welcome" User.Identity.Name;
}
Else {
// Not logged in, add a link to the login page
Welcome.text = "Please login!";
Welcome.navigateURL = "Signin.aspx";
}
}
script>
asp: hyperlink>
Introduction to Context.Items
I hope that the above examples can be explained that it is easy to write a web application only with the contextual information of the hand. So, if you can use the same method to access some contexts your application unique, isn't it good?
This is the use of context.items collection. It uses methods available in each part of the partial code participating in the processing request, and saves the request specific value for the application. For example, the same information can be used in the User Controls in the Global.asax, ASPX page, and page, can also be used by page calls.
Consider the Ibuyspy Portal (English) application example. It uses a simple homepage desktopdefault.aspx to display the door content. The contents of the display depends on the selected tab, and the user (if you have already pass the authentication) role.
Figure 2: iBuyspy Home
The query string contains the TabindedX and TabID parameters of the tab that is being requested. During the entire process of processing the request, this information is used to filter data to display to the user. http://www.ibuysportal.com/desktopdefault.aspx?tabindex=1&tabid=2 (English)
To use query string values, you need to first make sure it is a valid value, if not, you have to do some error handles. It is not a big string code, but do you really want to copy it in pages and components that use this value? of course not! In the portal example, even more places involve it, because once we know TabID, you can add additional information.
Portal uses query string values as parameters to construct a new PortalSettings object and add it to the Context.Items of the Global.asax's BeginRequest event. Since the start request is performed at each request, this allows values related to this tab to be available in all pages and components of the application. After the request is complete, the object will be automatically discarded - very neat! [Visual Basic Global.asax]
Sub Application_BeginRequest (Sender AS [Object], E AS Eventargs)
DIM Tabindex as integer = 0
DIM Tabid as integer = 0
'Get TabINDEX from query strings
IF not (Request.Params ("Tabindex") IS Nothing) THEN
Tabindex = int32.parse (Request.Params ("TabINDEX"))
END IF
'Get Tabid from query strings
IF not (Request.Params ("Tabid") IS Nothing) THEN
Tabid = int32.parse (Request.Params ("Tabid"))
END IF
Context.Items.Add ("PortalSettings", _
New PortalSettings (TabIndex, Tabid))
End Sub
[C # global.asax]
Void Application_BeginRequest (Object Sender, Eventargs E) {
INT TabINDEX = 0;
INT Tabid = 0;
// Get TabINDEX from query strings
IF (Request.Params ["TabINDEX"]! = null) {
Tabindex = int32.parse (Request.Params ["TabINDEX"]);
}
// Get Tabid from the query string
IF (Request.Params ["Tabid"]! = null) {
Tabid = int32.parse (Request.Params ["Tabid"]);
}
Context.Items.Add ("PortalSettings",
New PortalSettings (TabIndex, Tabid);
}
Desktopportalbanner.ascx User Control requests PortalSetting object from Context to access portal's name and security settings. In fact, this module is a typical synthetic example of Context in the operation. To clarify this, I have simplified the code and labeled all the places accessed by HTTP or application-specific Context with bold.
[C # desktopportalbanner.ascx]
<% @ Import namespace = "aspnetportal"%>
<% @ Import namespace = "system.data.sqlclient"%>
Public int Tabindex;
Public Bool ShowTabs = TRUE;
Protected string logofflink = ""; void page_load (Object sender, eventargs e) {
// Get portalSettings from the current context
PortalSettings PortalSettings =
(PortalSettings) Context.Items ["PortalSettings"];
// Dynamic Plip Portal Site Name
SiteName.Text = PortalSettings.PortalName;
// If the user is logged in, custom information
IF (Request.Isauthenticated == true) {
WelcomeMessage.Text = "Welcome"
Context.user.Identity.name "! <"
"span class = accent" "> | <" "/ span" ">"
// If the authentication mode is cookie, a logout link is provided.
IF (context.user.Identity.AuthenticationType == "forms") {
Logofflink = "<" "span class = /" accent / "> | span> / n"
" Logout"
"";
}
}
// Dynamic Display Portal Tab
IF (ShowTabs == True) {
TabINDEX = PortalSettings.ActiveTab.TabINDEX;
/ / Generate the tab list to display to the user
ArrayList AuthorizedTabs = new arraylist ();
INT AddedTabs = 0;
For (int i = 0; i TabStripdetails Tab = (Tabstripdetails) PortalSettings.desktoptabs [i]; IF (portalsecurity.isinroles)) { AuthorizedTabs.Add (Tab); } IF (addedtabs == tabindex) { Tabs.selectedIndex = AddedTabs; } AddedTabs ; } // Pull with the tab at the top of the page with the authorized tab / / List Tabs.DataSource = authorizedTabs; Tabs.DATABIND (); } } script> td> td> td> TR>