HttpContext.Current is not everywhere.

Source: Internet
Author: User
Tags apm httpcontext net thread

Original address: http://www.cnblogs.com/fish-li/archive/2013/04/06/3002940.html

Read Catalogue

    • Begin
    • The ubiquitous HttpContext
    • Where exactly is httpcontext.current saved?
    • HttpContext is not everywhere!
    • How do I get the absolute file path?
    • How do I access HttpContext in an asynchronous call?
    • Safe use of HttpContext.Current

The developers who understand the ASP know that it has a very powerful object HttpContext, and for convenience, ASP. NET also provides it with a static property httpcontext.current to access it, and today's blog intends to start with httpcontext.current.

Back to the top of the ubiquitous HttpContext

Because ASP. NET provides static attribute HttpContext.Current, it is very convenient to get the HttpContext object. It is for this reason that we often see the code that accesses httpcontext.current directly:

public classClass1{PublicClass1 () {StringFile=HttpContext.Current.Request.MapPath ("~/app_data/xxxxxx.xml");StringText=System.Io.File.ReadAllText (file);//.......... Other operations}Or use HttpContext.Current directly in some methodspublic voidXXXXX () {StringUrl=HttpContext.Current.Request.RAWURL;StringUsername=HttpContext.Current.session["Username"].ToString ();StringValue=(string) httpcontextcurrent. Items[ "key" ];} //even designed static properties public static string  XXX {get {return  (string) httpcontext< Span style= "color:red". current. Items[ "XXX" ];}}        

This kind of code, often can be seen in the Class library project, this shows the extent of its flooding.

Is there really no problem with this code? Some people would say: "I wrote the code is for the ASP, not for the console program, so there is no problem."

Is that really the case?

Back to the top httpcontext.current exactly where is it stored?

Indeed, in an ASP. almost any time, we can access httpcontext.current to get a HttpContext object, however, have you ever wondered how it is implemented?

If you haven't thought about it, I'll let you know today. Take a look at the following code:

protected voidPage_Load (ObjectSenderEventArgsE) {HttpContextContext1=HttpContext.Current;HttpContextcontext2 = System.  Runtime.  Remoting.  Messaging.  CallContext.  Hostcontext as HttpContext; bool isequal = object.  ReferenceEquals (Context1, CONTEXT2); Response.  Write (isequal);}                  

Guess what it's going to show?

This is the result I see, you can try it if you don't believe it.

From this code point of view, HttpContext is actually stored in the Callcontext.hostcontext attribute, if you are also curious about hostcontext, You can use your own Reflector.exe to see, I do not want to post code, because some types and methods are not public.

Let's take a look at how MSDN explains Callcontext.hostcontext:

Gets or sets the host context associated with the current line threads.

This explanation is very vague, but there are two key words we can write down: "Current thread", "association".

Is it something that is associated with the current line threads? That's what I understand.

Why do we have access to httpcontext.current everywhere in an ASP. Because ASP. NET will assign a thread to each request, the thread executes our code to generate the response, and even if our code is scattered in different places (class libraries), the thread will still execute them, so we can access the httpcontext.current anywhere and get to the " The current request "related HttpContext object, after all, the code is executed by the same thread, so the resulting HttpContext reference is the object that we expect to be related to the request.

Therefore, it is appropriate to design httpcontext.current to associate with the current thread.

Back to the top HttpContext is not everywhere!

What's the meaning of "current thread"? Why should I highlight the word?

Answer: 1. The current thread refers to the thread that is related to the current request. 2. In ASP. NET, some threads are not always related to the request.

Does it feel a little bit around the mouth? Isn't it easy to understand? Let's keep looking down.

Although in an ASP. NET program, almost all of the threads should be running in response to the request, but some threads are not running in response to the request, for example: 1. Callback for the timer. 2. Remove notifications from the cache. 3. The callback is completed asynchronously in APM mode. 4. Actively create threads or assign tasks to the thread pool to execute.

In these cases, if the thread executes to httpcontext.current, what do you think will be returned? Or is it a HttpContext instance reference? How is that, and which request is it associated with?

Obviously, in 1, 22 cases, access to HttpContext.Current will return null. Because there is a good chance that the task does not occur at all at run time. People who understand async should be able to easily understand the 3rd case (it is a conclusion) and the 4th case is even less necessary because it is not really the current thread.

Since this is the case, let's take a look at the code at the beginning of this article:

Publicclass1 () {string file = httpcontext. Current. Request. MapPath ( "~/app_data/xxxxxx.xml" string text = system. Io. File. ReadAllText (file); //.... Other operations }             

Imagine if Class1 was created at the timer callback or the cache removal notification, do you think it will work?

Do you have an answer in mind right now?

You might think: Why do I have access to httpcontext.current anywhere else and get HttpContext references? A: That's because ASP. HttpContext has been set to the Callcontext.hostcontext property described earlier before calling your code. HttpApplication has an internal method OnThreadEnter (), ASP. NET calls this method to switch HttpContext before calling external code, for example, whenever a callback is executed before the event handler for the pipeline executes, or when the synchronization context (Aspnetsynchronizationcontext) executes. After switching the thread's Callcontext.hostcontext property, our code can access the HttpContext reference. Note: The HttpContext reference is actually saved in the HttpApplication object.

Sometimes we will see "ASP." NET thread "This is the word I understand today: the current thread is a thread associated with a HttpContext, and because the thread is associated with HttpContext, it means that it is processing the request sent to ASP. Note: This thread is still the thread of the thread pool.

Back to the top how do I get the absolute path of a file?

In the timer callback or the cache removal notification, sometimes do need to access the file, but for developers, they do not know where the site will be deployed in the directory, it is impossible to write an absolute path, they only know relative to the site root directory relative path, in order to locate the file path, You can only call HttpContext.Current.Request.MapPath or HttpContext.Current.Server.MapPath to get the absolute path to the file. If HttpContext.Current returns NULL, how do I access the file?

In fact, the method is not MapPath, we can access Httpruntime.appdomainapppath to get the path of the site, and then stitching the relative path of the file:

See no: HttpContext.Current in the picture shows NULL, so if you call MapPath again, you will die!

Here I also advise you: try not to use Mappath,httpruntime.appdomainapppath is a safer choice.

Back to the top asynchronous call how do I access HttpContext?

I also mentioned earlier that when the asynchronous completion callback in APM mode, Access HttpContext.Current also returns NULL, what should I do now?

There are two kinds of answers: 1. Add a field to the type to hold the HttpContext reference (before the asynchronous start). 2. Assign HttpContext to the last parameter of the BeginXxx method (object state)

It is recommended that you prioritize the second approach, because you can prevent data members from accidentally being used when others are being maintained.

Back to top safely using HttpContext.Current

Sometimes we write generic libraries for ASP. NET or Windowsservice programs to use, such as tool methods for exception logging. For an ASP, we certainly want to record URLs, form values, cookies, and so on when an exception occurs, facilitating post-mortem analysis. But for windowsservice such programs, you certainly didn't want to record cookies? So how do you implement a common function?

The method is also simple, which is to determine whether httpcontext.current returns null, such as the following sample code:

public static voidLogexception (ExceptionEx) {StringBuilderSb=NewStringBuilder(); Sb.Append ("Exception Occurrence time:").Appendline (DateTime.Now.ToString ()); Sb.Appendline (ex.ToString ());If it's an ASP, you also need to record data such as url,form, cookies, etc.HttpContextContext=HttpContext.Current;If(Context!=Null//can run here, it is certainly in the process of ASP. We can safely access all the data of the request sb. Appendline ( "URL:" + context< Span style= "color:red". request. RAWURL); //also have to record what data, you come to realize it.  System. Io. File. Appendalltext ( "log file path" .< Span style= "Color:black" >tostring ()),            

is a judgment that solves all the problems, so please forget the following type of unsafe wording:

HttpContext.  Current.  Request.  RAWURL; HttpContext.  Current.  Server.  MapPath ("xxxxxx");              

The following methods are safe:

HttpContext.  Current; if//here to access something related to the request. }

HttpContext.Current is not everywhere.

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.