In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly explains "HttpContext.Current case Analysis". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Next, let the editor take you to learn "HttpContext.Current case Analysis"!
Ubiquitous HttpContext
Because ASP.NET provides the static property HttpContext.Current, it is very convenient to get the HttpContext object. It is for this reason that we often see code that accesses HttpContext.Current directly:
Public class Class1 {public Class1 () {string file = HttpContext.Current.Request.MapPath ("~ / App_Data/xxxxxx.xml"); string text = System.IO.File.ReadAllText (file); / /. Other operations} / / or use HttpContext.Current public void XXXXX () {string url = HttpContext.Current.Request.RawUrl; string username = HttpContext.Current.Session ["username"] .ToString () directly in some methods; string value = (string) HttpContext.Current.Items ["key"] } / / even designed as a static attribute public static string XXX {get {return (string) HttpContext.Current.Items ["XXX"];}
Such code can often be seen in class library projects, which shows the extent of its flooding.
Is there really nothing wrong with the code?
Some people might say: the code I wrote is for the ASP.NET program, not for the console program, so there is no problem.
Is that true?
Where exactly is the HttpContext.Current saved?
Indeed, at almost any time in an ASP.NET program, we can visit HttpContext.Current to get a HttpContext object, but have you ever wondered how it is implemented?
If you haven't thought about it, I'll tell you today. Please look at the following code
Protected void Page_Load (object sender, EventArgs e) {HttpContext context1 = HttpContext.Current; HttpContext context2 = System.Runtime.Remoting.Messaging.CallContext.HostContext as HttpContext; bool isEqual = object.ReferenceEquals (context1, context2); Response.Write (isEqual);}
Guess what it will show?
This is what I have seen. You can try it if you don't believe it.
Judging from this code, HttpContext is actually stored in the property CallContext.HostContext. If you are still curious about HostContext, you can use Reflector.exe to see it for yourself. I don't want to post any more code, because some types and methods are not public.
Let's take a look at how MSDN interprets CallContext.HostContext:
Gets or sets the host context associated with the current thread.
This explanation is very vague, but there are two keywords we can write down: [current thread], [association].
Is there something associated with the current thread?
That's how I understand it.
Why can we access HttpContext.Current everywhere when we are in an ASP.NET program?
Because ASP.NET allocates a thread for each request, this thread executes our code to generate the response result, even if our code is scattered in different places (class libraries), the thread will still execute them, so we can access HttpContext.Current anywhere to get the HttpContext object related to the [current request]. After all, the code is executed by the same thread. So the resulting HttpContext reference is the object we expect to be related to the request.
Therefore, it is appropriate to design the HttpContext.Current to be associated with the current thread.
HttpContext is not everywhere!
What does [current thread] mean? Why should I highlight this word?
A:
1. The current thread is the thread associated with the current request.
two。 In ASP.NET, some threads are not always associated with requests.
Do you feel a little tongue-twisting? Isn't it easy to understand? Let's keep looking down.
Although in an ASP.NET program, almost all threads should run in response to a request
However, there are some threads that do not run in response to the request, such as:
1. Callback of the timer.
2. Notification of removal of Cache.
3. Complete callback asynchronously in APM mode.
4. Proactively create threads or leave tasks to the thread pool to execute.
In these cases, what do you think will be returned if the thread executes to the HttpContext.Current?
Is it still an instance reference to HttpContext?
How is, which request is it associated with?
Obviously, in both cases, accessing HttpContext.Current will return null.
Because it is quite possible that the task does not have any requests at run time. People who understand asynchronism should be able to easily understand the third situation (think of it as a conclusion)
The fourth case does not need to be explained, because it is really not the current thread.
In that case, let's take a look at the code at the beginning of this article:
Public Class1 () {string file = HttpContext.Current.Request.MapPath ("~ / App_Data/xxxxxx.xml"); string text = System.IO.File.ReadAllText (file); / /. Other operations}
Imagine this: if Class1 was created during a timer callback or a Cache removal notification, do you think it would still work?
You should have the answer in your mind now, right?
You may wonder: why can I access HttpContext.Current and get HttpContext references anywhere else?
Answer: that's because ASP.NET has set HttpContext to the CallContext.HostContext property mentioned earlier before calling your code.
HttpApplication has an internal method OnThreadEnter () that ASP.NET calls to switch HttpContext before calling external code, for example, whenever the event handler of the pipeline is executed, or when the synchronization context (AspNetSynchronizationContext) performs a callback. After switching the thread's CallContext.HostContext property, our code can access the HttpContext reference. Note: the reference to HttpContext is actually saved in the HttpApplication object.
Sometimes we see the word "ASP.NET thread", and today is a good time to talk about my understanding of the word: the current thread is a thread associated with a HttpContext, and because the thread is associated with the HttpContext, it means that it is processing requests sent to the ASP.NET. Note: this thread is still a thread in the thread pool.
How do I get the absolute path to a file?
In timer callback or Cache removal notification, it is sometimes necessary to access files. However, for developers, they do not know the directory in which the site will be deployed, so it is impossible to write an absolute path. They only know the relative path to the root of the site. In order to locate the file path, they can only call HttpContext.Current.Request.MapPath or HttpContext.Current.Server.MapPath to get the absolute path of the file. If HttpContext.Current returns null, how do I access the file?
In fact, MapPath is not the only method. We can visit HttpRuntime.AppDomainAppPath to get the path of the website, and then stitch together the relative path of the file:
See: HttpContext.Current shows null in the picture, so if you call MapPath again, you will die!
Here I would also like to advise you: try not to use MapPath,HttpRuntime.AppDomainAppPath is the safer choice.
How to access HttpContext in asynchronous invocation?
I also mentioned earlier that when the callback is completed asynchronously in APM mode, accessing HttpContext.Current also returns null, so what should I do?
There are two answers:
1. Add a field to the type to hold the reference to HttpContext (before asynchrony starts).
two。 Assign HttpContext to the last parameter of the BeginXXX method (object state)
It is recommended that the second method be preferred because it can prevent data members from being accidentally used when maintained by others in the future.
Safe use of HttpContext.Current
Sometimes we write general class libraries for ASP.NET or WindowsService programs to use, such as tool methods for exception logging. For ASP.NET programs, we definitely want to record URL, form values, Cookie and other data when an exception occurs, so as to facilitate post-analysis. However, for programs like WindowsService, you certainly don't want to record Cookie, do you? So how to implement a general function?
The method is actually simple, which is to determine whether HttpContext.Current returns null, such as the following sample code:
Public static void LogException (Exception ex) {StringBuilder sb = new StringBuilder (); sb.Append ("exception occurrence time:") .AppendLine (DateTime.Now.ToString ()); sb.AppendLine (ex.ToString ()); / / if it is an ASP.NET program, you also need to record data such as URL,FORM and COOKIE HttpContext context = HttpContext.Current If (context! = null) {/ / if you can run here, you must be dealing with ASP.NET requests. We can safely access all the data sb.AppendLine ("Url:" + context.Request.RawUrl) of Request; / / you can implement what data is recorded by yourself. } System.IO.File.AppendAllText ("log file path", sb.ToString ());}
It's just a judgment that solves all the problems, so forget the following unsafe phrases:
HttpContext.Current.Request.RawUrl; HttpContext.Current.Server.MapPath ("xxxxxx")
The following methods are safe:
HttpContext context = HttpContext.Current; if (context! = null) {/ / access something related to the request here. } at this point, I believe you have a deeper understanding of "HttpContext.Current case Analysis". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.