Summary of ASP. NET Status Management

Source: Internet
Author: User
Tags javascript array

Due to the stateless nature of the HTTP protocol, in ASP. NET programming, each request is executed from the server to the pipeline process,
For ASP. NET pages, the Page object is re-created, and all controls and content are re-generated,
Therefore, if you want the status of the last page to be retained in subsequent pages, you must introduce the status management function.

ASP. NET provides eight methods to implement status management, which can help us retain status data between pages or throughout user sessions.
These methods are classified into two types: View status, control status, hidden domain, Cookie, and query string. data is sent to the client in different ways.
The Application Status, session status, and Profile will store the data to the server.
Although each method has different advantages and disadvantages, for small projects, you can choose the method that you think is the easiest to use,
However, for programs with high requirements, especially those with high performance and scalability,
The final difference may be very large when different methods are selected.

In this blog, I will talk about my views on ASP. NET status management.
Note: This article may not be suitable for small projects, because I am not concerned with ease of use.

Hidden-input

Hidden-inputThis name indicates all input tag elements of type = "hidden.
In the Chinese version of MSDN, it is also calledHide domain.
Hidden-input usually exists in HTML forms and is not displayed on pages,
But it can be submitted along with the Form. Therefore, it is often used to maintain the status of the current page. on the server side, we can use Request. Form [] to access the data.

Generally, I usually use hidden-input to save some intermediate results and maintain a series of statuses during multiple commits,
You can also use it to save some fixed parameters for submission to other pages (or websites ).
In these scenarios, I do not want users to see the data. Therefore, it is convenient to use hidden-input.

For more information about forms, refer to my blog: detail Form)

In the ASP. NET WebForm framework, we can use the HiddenField control to create a hidden-input control and operate it on the server,
You can also directly use hidden fields by hand, for example:

<input type="hidden" name="hidden-1" value="aaaaaaa" /><input type="hidden" name="hidden-2" value="bbbbbbb" /><input type="hidden" name="hidden-3" value="ccccccc" />

In addition, we can call ClientScript. RegisterHiddenField () to create a hidden domain:

ClientScript.RegisterHiddenField("hidden-4", "ddddddddd");

Output result:

<input type="hidden" name="hidden-4" id="hidden-4" value="ddddddddd" />

The main difference between these three methods for the generated HTML code is that they appear in different locations:
1. HiddenField control: it is determined by the position where HiddenField appears (inside form ).
2. RegisterHiddenField method: it is at the beginning of the form tag.
3. hidden-input: Where are you writing.

Advantages:
1. No server resources are required: The Hidden domain is sent to the client along with the page.
2. Extensive support: almost all browsers and client devices support forms with hidden fields.
3. Easy Implementation: hidden fields are standard HTML controls and do not require complex programming logic.

Disadvantages:
1. The status cannot be maintained between multiple page jumps.
2. Users can see that encryption is required when sensitive data is stored.

QueryString

The query string is a piece of data that exists at the end of the URL. The following is a typical query string example (text in red ):

http://www.abc.com/demo.aspx?k1=aaa&k2=bbb&k3=ccc

Query strings are often used for page data filtering, for example:
1. Add the paging parameter to the list page, list. aspx? Page = 2
2. added a range for the list page, Product. aspx? CategoryId = 5
3. display specific records, ProductInfo. aspx? Page = 3

For the query string usage, I add two points:
1. You can call HttpUtility. ParseQueryString () to parse the query string.
2. Repeated parameter names are allowed: list. aspx? Page = 2 & page = 3. Therefore, when modifying URL parameters, use the replacement method instead of the append method.
For more information about how to read duplicate parameters, see my blog: Request [] and Request. Params [].

Advantages:
1. No server resource is required: query string data is included in each URL.
2. Extensive support: almost all browsers and client devices support using query strings to pass parameter values.
3. Simple implementation: directly access Request. QueryString [] on the server to read data.
4. Simple page transfer value: either <a href = "url"> or Response. Redirect (url) can be implemented.

Disadvantages:
1. There is a length limit.
2. the user is visible and cannot store sensitive data.

Cookie

Because the HTTP protocol is stateless, the WEB server cannot tell whether the requests sent by a browser come from the same browser. Therefore, additional data is required for session maintenance. Cookie is such an additional piece of data that is transmitted along with the HTTP request.
Cookie is a short text message, which is transmitted between the Web server and the browser along with user requests. Cookie contains information that can be read by Web applications every time a user accesses the site.

Cookie has more attributes than hidden-input and QueryString. Many browsers can directly view these attributes:

Because cookies have these attributes, more functions can be implemented in client status management,It plays an irreplaceable role especially in implementing client sessions.

For more information about cookies, refer to another blog:

Advantages:
1. configurable expiration rules: cookies can be permanently stored on the client or cleared when the browser is closed.
2. No server resources are required: cookies are stored on the client.
3. Simplicity: Cookie is a lightweight text-based structure that contains simple key-value pairs.
4. Data Persistence: compared with other client status data, cookies can be saved for a long time.
5.Good scalability: The Cookie read/write process goes through the ASP. NET pipeline and has unlimited scalability.

Here I want to explain the concept of Cookie [good scalability], for example:
1. I can save the Cookie to the database without modifying the existing project code.
2. Set SessionId to a temporary Cookie generated by ASP. NET to persistent storage.

Disadvantages:
1. The size is limited.
2. Increase the length of the request header.
3. As you can see, encryption is required for storing sensitive data.

ApplicationState

The application status is maintained using the HttpApplicationState method. The Code is as follows:

Application.Lock();Application["PageRequestCount"] = ((int)Application["PageRequestCount"]) + 1;Application.UnLock();

For this method,I do not recommendBecause:
1. Similar to static variables, you can directly use static variables without Dictionary lookup.
2. Select a strongly typed set or variable to avoid packing and unpacking.

ViewState, ControlState

View status and control status. The two are similar. A hidden-input element is displayed on the page:

<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="......................" />

The control status is introduced in ASP. NET 2.0. It cannot be disabled compared with the view status.
Because they are used in the same way, and the view status is based on the control status implementation logic, I will not distinguish them.

In ASP. in the early days of NET, Microsoft introduced a large number of server controls to help developers improve development efficiency, and introduced the event programming mechanism into ASP. NET, and invented ViewState.

Although this method can simplify the development workload, there are some restrictions and disadvantages:
1. View status data can only be used for postback ).
2. [misuse] of view status may lead to a large HTML generated, which leads to a vicious circle:
A. Excessive ViewState will consume a large amount of server CPU resources during serialization,
B. the HTML output generated by a large ViewState will also be large, which will waste network resources on the server,
C. A large ViewState output causes the form to occupy Network Resources of the client when it is submitted next time.
D. If the ViewState data is uploaded to the server, deserialization consumes a lot of server CPU resources.
Therefore, throughout the interaction process, the user has been waiting and the user experience is poor.

In the age of ASP. NET, ViewState was an amazing invention.
However, in many methods of ASP. NET performance optimization, the "Close ViewState" option is placed in the headlines.
Why? You can think about it yourself.

Some people think that the program I am working on is only used in the LAN and there is no problem with ViewState!
However, those may not have thought about:
1. In the future, users may deploy it on the internet for Operation (for products, they will encounter major customers ).
2. Early project design and planning have a huge impact on development and maintenance in the future, because many basic components are usually developed in the early stage.
It may be too late to disable ViewState when either of the two conditions occurs.

For view status, I think it introduces more complicated problems than it solves,
Therefore, I don't want to spend time organizing its advantages and disadvantages. I just want to say:Turn it off and disable it in web. config.

In addition,I do not reject the use of server controls, I think: You can use server controls to display dataBut do not use it for sending back.

If you still think that the view status is indispensable, I suggest you look at the ASP. NET MVC Framework to see if ASP. NET programs can still be written without the view status.

Session

Session is a server Session technology implemented by ASP. NET. It allows us to conveniently store user-related Session data on the server.

I think there is only one SessionAdvantages: The simplest Server session implementation method.

Disadvantages:
1. When mode = "InProc", data is easy to lose. Why? The website will be restarted for various reasons.
2. When mode = "InProc", the more things saved by the Session, the more memory occupied by the server. For websites with a large number of online users, the memory pressure on the server will be relatively high.
3. When mode = "InProc", the scalability of the program will be affected because the memory of the server cannot be shared among multiple servers.
4. When the out-of-process mode is adopted, all session data is prepared for you (deserialization) No matter whether you use session data in each request. This is a waste of resources.
5. If you do not close the Session, SessionStateModule will always be working. Especially when you use the default settings, a series of calls will be executed for each request, wasting resources.
6. Block multiple requests initiated by the same client (default ).
7. Non-Cookie sessions may lose data (regenerate expired session identifiers ).

These shortcomings of Session also remind us:
1. When the website has a large number of online users, do not use Session to save large objects.
2.In intensive AJAX websites or websites that use iframe in a large number, you should pay attention to the server blocking problem that may be caused by Session.
3. When using the out-of-process mode, you do not need to access the Session page. Otherwise, server resources will be wasted.

If you want to learn more about the Session characteristics and my views on the Session, you can visit my blog: Session. Is it necessary to use it?

The essence of Session is as follows:
1. SessionId + server dictionary: the server dictionary stores all session data of a user.
2. Use SessionId to identify different clients: SessionId is usually sent to clients in the form of cookies.

I think it is very useful to understand the nature of Sesssion, because you can learn from and implement your own server session methods.

I also want to talk about the Session:
Some new users prefer to use Session to implement identity authentication. This is an incorrect method.
If your ASP. NET application requires authentication, use Forms authentication or Windows authentication.

Profile

ProfileIn the Chinese version of MSDN, it is calledConfiguration File PropertiesThis function is introduced in ASP. NET 2.0.

ASP. NET provides this function to simplify the reading and writing of user-related personalized information.
The simplification mainly involves three aspects:
1. It is automatically associated with a user. It is supported by logged-on users or non-logon users.
2. We do not need to design a table structure for storing user personalized information. We only need to modify the configuration file.
3. We do not need to implement the data loading and storage logic. The ASP. NET Framework has been implemented for us.

To use Profile, we first define the User Personalization information in web. config:

<profile>    <properties>        <add name="Address"/>        <add name="Tel"/>    </properties></profile>

Then, you can use the following in the page:

Why?
The reason is that ASP. NET has created a new type for US based on web. config:

using System;using System.Web.Profile;public class ProfileCommon : ProfileBase{    public ProfileCommon();    public virtual string Address { get; set; }    public virtual string Tel { get; set; }    public virtual ProfileCommon GetProfile(string username);}

With this type, ASP. NET will create a ProfileCommon instance when we access the HttpContext. Profile attribute.
It is also because of the strong Profile type mechanism that the smart notification function is available only when the Profile is used.

If we want to provide this support for Unlogged anonymous users, we need to modify the configuration:

<profile>    <properties>        <add name="Address" allowAnonymous="true" />        <add name="Tel" allowAnonymous="true"/>    </properties></profile><anonymousIdentification enabled="true" />

Each attribute in Profile can also specify the type, default value, and serialization method. Therefore, the scalability is better.

Although Profile looks beautiful, there are few people who use Profile.
For example, I don't need it, and no one has ever seen it.
Why?

I personally think: Like MemberShip, it is a weakness.
Generally, we create a User table for User information. When adding User information, we add fields.
I think it would be better to concentrate on data like this, instead of maintaining some data by me and others by ASP. NET.

Another special case is that we do not create a User table and directly use MemberShip. Therefore, it is necessary to use Profile to save the MemberShip without information.

Make a summary for Profile:
Advantages: Easy to use.
Disadvantages: Not practical.

Comparison and summary of various status management

The eight State management technologies of ASP. NET are introduced in the previous sections. I plan to summarize them here.

Client Server
Data security Difference Good
Data Length limit Yes Limited by hardware
Occupy server resources No Yes
Cluster scalability Good Difference

The table mainly describes the important indicators related to data storage and server horizontal scaling.

Below I will explain the results of the table.
1. client-side status data (hidden-input, QueryString, Cookie ):
A. Data is visible and changeable for users, so data is not secure.
B. QueryString and Cookie have length restrictions.
C. The data is on the client, so it does not occupy server resources. This feature is very important for websites with a large number of online users.
D. The data is on the client, so there is no coupling relationship with the server, and the WEB server can easily implement horizontal scaling.

2. server-side status data (ApplicationState, ViewState, ControlState, Session, Profile ):
A. Data is invisible to users, so it is secure. (ApplicationState, Session, Profile)
B. The length of a number is limited by hardware only. Therefore, exercise caution when selecting websites with a large number of online users.
C. For status data stored in the memory, because the memory cannot be shared, horizontal scaling is limited.
D. If the status data is saved to a machine, a single point of failure may occur, which may also limit the horizontal scalability.

We can also draw the following conclusions from this table:
1. If you are very concerned about data security, you should first choose the server-side status management method.
2. If you are concerned about the horizontal scalability of the server, you should first choose the client's status management method.

Select session Status

Next, let's take a look at the session status. It has some relationships with status management, which is a similar concept.

When talking about the session status, I want to declare that the session Status and status are not the same thing.

The status mentioned above is divided into two types:
1. Status between pages.
2. Status within the application scope.

The session Status refers to the status of a user between multiple operations.
During the user's operation, it is possible that the status needs to be continuously used between pages,
It is also possible that the server program has been restarted, but the data is still valid.
Therefore, this state data is more persistent.

In ASP. NET, Session status has two options: Session or Cookie.
The former is implemented by ASP. NET and may depend on the latter.
The latter is implemented by the browser, and ASP. NET provides the read/write method.

So which one do you choose?
If you want to ask me this question, I will definitely say:Select Cookie!

The following are the reasons why I chose cookies to enable session Status:
1. There will be no server blocking issues.
2. Do not occupy server resources.
3. horizontal scaling is not limited.
4. Expired settings are also supported and more flexible.
5. You can directly use session data on the client.
6. More flexible session data loading policies can be implemented.
7. good scalability (due to the scalability of ASP. NET pipelines)

If you choose to use cookies for session Status, pay special attention to the following three points:
1. It is not recommended to save sensitive data unless it is encrypted.
2. It is only suitable for saving short and simple data.
3. If the session data is large, you can save the user ID on the client. The server can load and save the data.

Some people may think that each technology has its own advantages and disadvantages and has its own application fields.
I agree with this sentence.
However, we need to be clear that the scale of each project is different, and the performance and scalability requirements are also different.
For a small project, selecting a method is not a problem,
However, for large-scale projects, we must choose between them.
The goal of the trade-off is: the fewer the packages, the better, because people do too much packaging, there will be more restrictions,
Therefore, do not focus only on the convenience of current calls. In fact, you can simplify complicated calls as long as you are willing to pack them.

Change development methods and discover new methods

Recall: Why do I need status management in ASP. NET?
A: because it is related to the HTTP protocol, the server does not save the status of the last page of each request.

Why do Windows calculators (such) do not need to consider session issues?
A: Because the interfaces of such programs do not need to be regenerated, any variable can indicate the status.

Let's look at this scenario:

The left side of the image is a list page that allows you to adjust the priority of each record, but there are two requirements:
1. When moving each record, you must enter a reason for adjustment.
2. After the reason is entered, the record can be adjusted multiple times at will.

Obviously, this task must be completed in a stateful manner.

In the face of this problem, you can think about which ASP. NET-supported status management method is very troublesome.

What should I do?

My solution: Create a JavaScript Array and use each array element to save the status of each record,
All user interaction operations are implemented using AJAX, so the page will not be refreshed, And the status in JavaScript variables will remain valid.
Therefore, it is easy to solve this problem.

This case also reminds us that when all the status management functions provided by ASP. NET are inappropriate,
We need to change the development method.

Why is there a [stateless] Problem in WEB programming, but not in desktop programming?
I think it is related to the HTTP protocol, but there is no absolute relationship.
As long as you can ensure that the page is not refreshed, you can maintain the Page Status with JavaScript variables like the desktop program.

If you believe that reading this blog has some benefits, click 【Recommendation] Button.
If you want to discover my new blog more easily, click 【Follow Fish Li].
Because my enthusiasm for writing is inseparable from your support.

Thank you for reading this article. If you are interested in the content of my blog, please continue to follow up on my blog. I am Fish Li.

Related 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.