Some details that ASP. NET often ignores

Source: Internet
Author: User

Address: http://www.cnblogs.com/fish-li/archive/2013/05/28/3104750.html

Reading directory

  • Start
  • HttpContext. Current is not everywhere
  • Application_Start exception and IIS Classic Mode
  • QueryString and Form allow duplicate keys
  • Ashx Reuse
  • Currently logged on user information is sometimes not available
  • Timer may not work
  • Session and complex data types
  • JSON serialization of DateTime
  • Recruitment Information

Some time ago I encountered a problem: Why does the timer sometimes not work in ASP. NET programs?

This problem looks strange, and the code seems to be correct, but the results are inconsistent with expectations.
In fact, this is an easily overlooked section in ASP. NET applications. Later, I thought about such details. Today I will write down all the details that I can think of easily overlooked. I hope you will be careful with these questions.

I have mentioned some of my previous blogs separately, so I listed them in this blog. However, I will only briefly describe the content I have talked about before.

Returning to the top of HttpContext. Current is not everywhere

This problem is the one I mentioned in my blog last month.

Access HttpContext. Current in the following scenarios will return null
1. Timer callback.
2. Cache removal notification.
3. Callback is completed asynchronously in APM mode.
4. Actively create a thread or submit the task to the thread pool for execution.

Therefore, pay attention to this issue when writing a class library.

Return to the top Application_Start exception and IIS Classic Mode

When you run an ASP. NET Program in IIS6 or II7 Classic mode, if an uncaptured exception is thrown in the Application_Start eventThis exception is displayed once.

For more details about this problem, click: http://www.cnblogs.com/fish-li/archive/2013/03/24/2979780.html

Return to QueryString at the top. The Form allows duplicate keys.

We often see collections, such as Hashtable and Dictionary, which require that keys be unique. However, the QueryString and Form set instances of HttpRequest areDuplicate keys allowedWhen duplicate keys are encountered and the set is accessed through the indexer,Concatenates all element values corresponding to the KEY with commas.

Why? Because the two sets are of NameValueCollection type, similar to Headers.

Because this particularity is different from our common situation, we need to pay attention to this difference. Of course, sometimes we can use this behavior to meet some special requirements, for more information about this details, see: http://www.cnblogs.com/fish-li/archive/2011/12/06/2278463.html, In this blog, also introduced the two indexers of HttpRequest is worth noting.

Back to Top ashx Reuse

Many ASP. NET developers should have created the ashx file, for example, the following:

public class Handler1 : IHttpHandler {    public bool IsReusable {        get {            return false;        }    }

I think many people will be curious about the IsReusable attribute, so I checked the definition of IHttpHandler and found this explanation,

// Abstract: // obtain a value indicating whether other requests can use the System. Web. IHttpHandler instance. //// Return result: // true if the System. Web. IHttpHandler instance can be used again; otherwise, false. Bool IsReusable {get ;}

It can be reused. Some people who are concerned about performance may change it to return true,In fact, everything is the same, because it does not work.

The reason does not work is explained in this blog: http://www.cnblogs.com/fish-li/archive/2012/01/29/2331477.html

Back to the top, the current Login User information is sometimes not available

In ASP. NET, the following methods are provided to obtain the information of the current user, for example:

If (HttpContext. Current! = Null) {// check whether the current user is a logged-on user bool isAuthenticated = HttpContext. current. request. isAuthenticated; // obtain the userName string userName = HttpContext of the current request. current. user. identity. name ;}

However, this code is placed in different places, but the effect is quite different.

Recently I encountered a problem: someone asked me why I always fail to use the User Name of the current user.
The website uses Windows identity authentication. Therefore, all requests are authenticated by IIS. Theoretically, the isAuthenticated variable should return true, userName should be the user name (Windows login name) of the current request. However, during debugging, the value of isAuthenticated is false, and the subsequent Code directly throws a null reference exception, it's strange because the User object is null, right?

In this case, we should check where the code is called.
As a result, I found that the code was called in an HttpModule and occurred in the BeginRequest event of the subscribed HttpApplication. Find the cause,At this time (at this stage), the User object has not been constructed even though ASP. NET identity authentication checks,Access now, of course, the result is not obtained.

From the point of conscience, this is really not a pitfall left by ASP. NET. Only some people do not know about pipeline events.

Returning to the top of Timer may not work

Sometimes we may encounter some requirements such as the execution of scheduled tasks, so some people may think of using the timer to implement, in. net framework, there are two Timer types that can be used for ASP. NET environment, however, Timer may not work, and the specific performance will make it hard for you to describe: do not know when the Timer will stop working.

This is a strange problem: when you are in debugging mode, the timer always works normally, but when you deploy the website, it takes longer to run, the timer is not working properly.

Why?
The answer is:After a website is not requested for a period of time, the process is recycled (released) by IIS ).
Therefore, the ASP. NET program is not suitable for executing a [Long timer] scheduled task, unless you can accept the timer to stop working.
A similar problem is that a method is passed to the Win32 program as a callback method in the ASP. NET program, and no response is returned for the callback.

For this reason, we recommend that you use a Windows Service program to implement a Long timer task or a program that receives Win32 callbacks.

Back to the top Session and complex data types

The Session has three working modes. For the ASPX page, the EnableSessionState command has three optional values: true, false, and ReadOnly.

EnableSessionState = "false", which is easy to understand: No Session is used.

EnableSessionState = "ReadOnly", literally, the Session is read-only.
The read-only control cannot be modified. However, the read-only mode of the Session indicates that you can modify the control, but I will not save your modification. There is no problem with this understanding.

EnableSessionState = "true" indicates that the Session supports readable and writable data.
After you update the Session content, all Session data of the current Session will be resaved.

In-process sessions are easy to lose and do not support data sharing among multiple Web servers. Therefore, there are not many people who choose this method. Most users choose status service or SQL Server to save the data, there is a problem to be noted here: when the Session mode is EnableSessionState = "true", if you access a complex object (not a system value type or a string ), no matter whether you modify it or not, the Session will be saved. For non-Process sessions, the SAVE operation means that serialization is required, and network transmission overhead may occur, which may affect the performance.

If the preceding description is not easy to understand, see the following sample code:

string sessionValue = Session["s2"] as string;if( sessionValue == null ) {    Session["s2"] = "Fish Li";    sessionValue = Session["s2"] as string;}

When this page is run for the first time, the Session is modified, so there will be a save operation. However, the subsequent access will not save the action.

Let's look at another piece of code:

// TestData is a custom type. TestData sessionValue = Session ["s1"] as TestData; if (sessionValue = null) {Session ["s1"] = new TestData {IntValue = 5, strValue = "Fish Li"}; sessionValue = Session ["s1"] as TestData ;}

Each time you run this code, a save operation occurs (as long as it is EnableSessionState = "true ").

I will repeat it again: this problem only occurs when EnableSessionState = "true" and complex objects are accessed (not system value type or string type. This problem has little impact on internal sessions, but it has some impact on the performance of external sessions, it depends on the data volume of the Session and the concurrency of the user.

To list this problem, I just want to tell you: if you really need to use the Session, please try to save the simple data [immutable] in the Session, in particular, do not keep the default Session settings (EnableSessionState = "true ").

To test this problem, implement a custom SessionStateStoreProviderBase derived class, and then debug and observe. The two indexers of SessionStateItemCollection will also give you an answer.

Return to JSON serialization of DateTime at the top

In SP. in NET3.5, Microsoft is ASP. NET is designed as a tool class for JSON serialization. web. script. serialization. javaScriptSerializer, which is widely used and has better compatibility than the JSON serialization class in WCF. However, there is a problem with this class. When serializing the DataTime type, the results it generates will make everyone feel awkward. In fact, the serialization result is still a small problem, write a conversion function on the front end. However, if you needObject persistence using serialization and deserialization Methods, You will encounter problems, such as the following code:

DateTime dt1 = DateTime.Now;JavaScriptSerializer jss = new JavaScriptSerializer();string json = jss.Serialize(dt1);DateTime dt2 = jss.Deserialize<DateTime>(json);context.Response.Write(dt1 == dt2);

The result displayed by the browser is surprising. It turns out to be: False.

This reason is related to the time format of JavaScript. It uses UTC time. However, this reason is unacceptable. After all, other deserialization methods can restore objects, for example, both binary serialization and XML can correctly restore objects. No way, this is only a pitfall. Therefore, if you want to perform Object Persistence operations, try not to select JSON serialization.

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.