About contexts (context)/1 (Transfer ms)

Source: Internet
Author: User
Tags closing tag header http request httpcontext log
About context
Susan Warren.
Microsoft Corporation
January 14, 2002

One of the most common problems in writing a WEB application is to let the code know its execution context. Let's use a simple example, a personalized page, to illustrate this problem:
Please log in.
And
Welcome susan!
Although it may seem simple, even this small Web UI still requires several pieces of information, and the information changes every time the page is requested. We need to know the following:
    1. Does the user log in?
    2. What is the user's display name?

More commonly, the question is, what is the only context that is required each time the page is requested? And how do you write code so that you can take this information into account?
In fact, because of the stateless nature of HTTP, Web applications may need to track many different context fragments. When a user interacts with a Web application, the browser sends a series of independent HTTP requests to the Web server. The application itself must organize these requests into experiences that are pleasing to the user, and it is critical to know the context of the request.
ASP introduces several internal objects, such as RequestAnd ApplicationTo help track the context of the HTTP request. ASP.net completes the next step and bundles these objects together with several other context-related objects to form an extremely convenient internal object Context
Contextis an object of type System.Web.HttpContext (English). it as ASP.net PageThe properties of the class are exposed. You can also get the object from the user control and business object (described in more detail below). The following is a partial list of the objects formed by HttpContext:
Description of the Object ApplicationA collection of keyword/value pairs for values that can be accessed by each user of the application. Application is System.Web.HttpApplicationStateType. applicationinstanceAn actual running application that exposes some request handling events. These events are handled in Global.asax, HttpHandler, or HttpModule. CacheThe ASP.net cache object, which provides programmatic access to the cache. Rob Howard's asp.net Caching column (English) gives a detailed description of the cache. ErrorThe first error (if any) encountered while processing the page. For more information, see Rob's Exception to the rule, Part 1 (English). ItemsA collection of keyword/value pairs that can be used to pass information between all components that participate in processing the same request. Items are System.Collections.IDictionaryType. RequestInformation about the HTTP request, including browser information, Cookies, and values passed in the form or query string. Request is System.Web.HttpRequestType. ResponseSettings and content for creating HTTP responses. Response is System.Web.HttpResponseType. ServerThe server is a utility class with some useful helper methods, including Server.Execute ()Server.MapPath ()And Server.HTMLEncode ()。 Server is System.Web.HttpServerUtilityThe object of the type. SessionA collection of keyword/value pairs of values that can be accessed by an individual user of the application. Session is System.Web.HttpSessionStateType. TraceASP.net's TraceObject that provides access to the tracing feature. For more information, see the article Rob wrote tracing (English). UserThe security context for the current user, if they have been authenticated. Context.User.Identity is the name of the user. User is System.Security.Principle.IPrincipalThe object of the type.
If you are an ASP developer, you should not be unfamiliar with some of the objects described above. Although there are some improvements, generally speaking, their role in asp.net is exactly the same as in ASP. Context Basics
ContextSome of the objects in are also upgraded to PageThe top-level object in. For example Page.Context.ResponseAnd Page.ResponseRefers 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");

can also be used from business objects ContextObject. HttpContext.Currentis a static property that makes it easy to return the context of the current request. This is useful in a variety of ways, and here is just a simple example of retrieving an item from the cache of a business class:

[Visual Basic]

' Get request Context Dim _context As HttpContext = HttpContext.Current ' Get cache DataSet Dim _data As DataSet = _context. Cache ("myDataSet")

[C #]

Gets the request context httpcontext _context = HttpContext.Current; Gets the dataset DataSet _data = _context in the cache. Cache ("myDataSet");
context in the Operation
ContextObject for some common asp.net "how ...?" The question provides the answer. Perhaps the best way to illustrate the value of this valuable object is to show it in action. Here are some of the most ingenious things I know ContextSkills.

How do I generate a asp.net trace statement from my own business class?


Answer:Very simple! Use HttpContext.CurrentGet Contextobject, and then call the Context.Trace.Write ()

[Visual Basic]

The Imports systemimports system.webnamespace context ' demo generates a ASP.net ' trace statement from the business class.  Public Class traceemit Public Sub somemethod () Gets request context Dim _context as HttpContext = HttpContext.Current ' writes trace statements _context using context. Trace.Write ("in Traceemit.somemethod") End Sub-end Classend Namespace

[C #]

The Using system;using system.web;namespace context{//demo generates a ASP.NET//trace statement from the business class.  public class Traceemit {public void SomeMethod () {//Get request Context HttpContext _context            = HttpContext.Current; Write trace statement _context using context.        Trace.Write ("in Traceemit.somemethod"); }    }}

How can I access session-state values from a business class?


Answer:Very simple! Use HttpContext.CurrentGet Contextobject, and then access the context.session

[Visual Basic]

The Imports systemimports system.webnamespace context ' demonstrates access to asp.net internal ' sessions from the business class. Public Class usesession Public Sub somemethod () ' Get request context Dim _context as HttpContext = H Ttpcontext.current ' Access internal session Dim _value as Object = _context. Session (' Thevalue ') end Sub-end Classend Namespace

[C #]

Using system;using system.web;namespace context{//demo access asp.net internal//Session public class Usesession {p from the business class            ublic void SomeMethod () {//Get request context httpcontext _context = HttpContext.Current; Access internal Session Object _value = _context.        session["Thevalue"]; }    }}

How can I add standard headers and footers to every page of an application?


Answer:Processing the application's beginrequestAnd endrequestevent, and use the Context.Response.WriteGenerates HTML for headers and footers.
Technically, it can be handled in HttpModule or by using Global.asax beginrequestSuch an application. HttpModules is difficult to write, and as this example shows, the functionality used by a simple application usually does not use it. Therefore, we use the application-scoped Global.asax file.
As with ASP pages, some intrinsic asp.net contexts have been promoted to properties of the HttpApplication class, where the class represents the Global.asax inheriting class. We don't need to use HttpContext.CurrentGet the ContextThe reference to the object; it's global.asax. is already available in.
In this case, I put the
Figure 1: Example of standard headers and footers rendered in the browser
This is a simple example, but you can easily extend it to include standard headers and navigation, or just output the corresponding <!--#include--->Statement. Note that you should consider using the ASP.net user control if you want the header or footer to contain interactive content.

[somepage.aspx Source code-content sample]

<font face= "Arial" color= "#cc66cc" size= "5" > General page Content </FONT>

[Visual Basic Global.asax]

<%@ application language= "VB"%><script runat= "Server" >      sub Application_BeginRequest (sender as Object, e as EventArgs)           ' Generate Header          context.response.write ("

[C # Global.asax]

 <%@ Application Language= "C #"%><script runat= "Server" >         void Application_BeginRequest (Object sender, EventArgs e) {             //Generate Headers              Context.Response.Write ("

How do i show welcome information after a user has been authenticated?


Answer:Test UserThe context object to see if the user is authenticated. If yes, and from UserObject gets the user name. Of course, this is the example at the beginning of this article.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.