Choose from
Blog of Timmy3310
ViewState is a new way to save in .NET (actually also old bottles of new wine); we know that traditional web programs have several ways:
1, Application This is the global saving area in the web application life period, and the data saved in Application is globally effective; in ASP.NET, there is an application pool, where several (or dozens) applications are saved. Program example, each request will take an instance from the pool to handle the request. This instance will not accept other requests before the request is completed; this will have a problem, and there may be multiple applications at the same time, that is, multiple threads These threads have the possibility of accessing Application, so it is necessary to consider the problem of thread synchronization when processing objects in Application; actually implementing a thread lock inside the Application object, calling it itself Add, Remove and other methods The lock-up and unlocking operation will be automatically called, but for performance consideration, the Application does not automatically process thread synchronization for the process directly through the indexer or other mode, and the Application is not automatically processed. :
Application.lock ();
((int) Application ["count"]) ;
Application.unlock ();
It is worth noting that after calling the Lock, if there is no display unlock, then the Application object will automatically unlock when this request is over, which prevents the problem of deadlocks, but for the tacity of the code, call LOCK And the modification should be called an unlock method immediately.
Application object is essentially a HASH table, and the object is stored according to the key value. Since the object is globally and stored in the server, and there is a multi-thread to access, there is more access to more access, less modification and is a global At least most of the data, such as counters or database connection string, etc..
2, session inside the ASP.NET, there is a stateApplication to manage the session, actually a secondary process, handle the session expiration, special requests created, the secondary process will call the status server when receiving each request. You can get a different status server through Web.config) to get the session. If there is no session that should be SessionID, you will create a new one, then bind to the context; Different from the ASP, the SESSION status server has more In addition, three are currently in ASP.NET: 1) InprocStateClientManager This is a traditional session save method, but there is still some subtle differences 2) SQLSTATECLIENTMANAGER This is saving session to database mode 3) OutofprocStateClientManager This is saving session to process The SESSION mechanism of the ASP.NET has a feature, which is to process the SESSION's auxiliary process and the status server that saves session is separated. According to MSDN, there is the following benefits: "Because memory used for session status is not in ASP.NET In the auxiliary process, the recovery from the application fault can be implemented. "" Because all status and secondary processes are not stored together, you can clean the application across multiple processes. This partition can significantly improve multiple The application is available and scalability on the computer. "" Because all status is not stored together with the secondary process, you can partition the application across multiple auxiliary processes running on multiple computers. "ASP. NET's session mechanism personal point of view, the feeling flexibility is better, the internal implementation is also clever, but actually because there is no test, it will not be as beautiful as it is saying it, I don't dare to pack. Have the opportunity, I will write an article separately to discuss the SESSION mechanism within ASP.NET. 3, cookie is nothing to say, actually ASP.NET and ASP cookies have no separate, perhaps this technology is hidden, and more dependent on client implementation, MS has no improvement.
4, ViewState This is our focus today; actually viewState is not mysterious, it is a hidden field, but it is the basis of the server control status; unfamiliar friends can use IE to view the HTML source code, find a name "__viewstate "The Hidden field, which has a large stack of seven-eight-tor der, this is the ViewState of the page.
People who have done a web program may have this painful experience, sometimes in order to handle the more complex features above, often add a lot of Hidden, then use a lot of judgment to analyze the current state in the server side, write up annoying It is more difficult to write the code. In fact, ViewState is the function of helping our system to save the control status, and the server-side control can save the status between multiple requests. Ok, introduce it to this, today we are not discussing the use of ViewState, but instead to explore the essence of this thing. We first built a test page: <% @ page language = "c #" codebehind = "viewStatetest.aspx.cs" autoeventwireup = "false" inherits = "csdntest.ViewStateTest"%>
Private void btnpostback_click (Object sender, system.eventargs e) {[1] Response.write ("ViewState:" Request.Params ["__ viewState"] "" "); [2] string decodevalue = Encoding. Utf8.getstring (Request.Params ["__ viewState"]); [3] Response.write ("ViewState Decode:" DecodeValue "); [4] Object ViewState = (New Losformatter ()). Dequest.Params ["__ viewstate"]); [5] Response.write ("ViewState Object:" ViewState.gettype (); Name)
For convenience, I added a line number; the first line we played the value of viewstate, what is the second line? In fact, a string of ViewState is saved to the client is the internal ViewState after serialization, so we encoded the base64, so we encode the base64-encoded string and then played again; as for the fourth line, I don't say it first, first look at the results: After running, there is no, in addition to buttons and checkbox (nonsense :)), we click the button, then the results are as follows:
[A] ViewState: DDWXMJU2MDI5MTA3OZTSPGNOA1RLC3Q7PJ6GG0QZM 7GACYWCY0HNRCT9TODA == [b] ViewState Decode: T <1256029107 ;; L> D3i S-! T [C] ViewState Object: Triplet
Then we come to analyze this result, the viewstate is the value of the viewState to the client, and the value after the Base64 anti-encoding is displayed. It seems that it seems to be seen from here, and there is a: Triplet? What is this, let's go back to the above code: Object viewState = (new losformatter ()). DeSerialize (Request.Params ["__ viewstate"]);
Note We use a Losformatter class. In fact, this class is an ASP.NET to provide serialized classes for ViewState. It has two methods. One is serialize, which is serialized an object, one is deserialize, is deserialization, We use the reverse selecentered approach to direct the viewState directly into an object, then call the type of object, this object is: Triplet type, actually saving the viewstate saved in the ASP.NET is this type, we Let's analyze LosFormater first, then let go. Let's come back to see the result B: T <1256029107 ;; L> D3i S-! T, actually see its sequence in general The way is very simple, it is to determine the type of sequential object. If it is not a direct serialization type, record its type, then in recursive serialization, we look at "T" in B. That is to indicate this type of Triplet, this type has three properties, including between "<" and ">", with ";" segmentation, and the last D3i S-! T. I analyze should be a prevention ViewState is changed, this is not very sure, because the anti-compilet code is really ugly, I just didn't look carefully after I learned. We have just analyzed the value of the viewState in Page is Triplet, in fact, this class is checked in the MSDN, it is an object containing three objects, saying simple point, it is a three Big box (it seems to be more confused, huh, it has three properties: first, second, thrid :), represents three objects, respectively. Corresponding to Page, First is the return value of page.gettypeHashCode (), this method is a protected virtual method defined by system.Web.ui.page, returns an integer, the class generated by the ASPX file, because This class is ASP.NET responsible for generating source code and compiled in the running period, which calculates a large amount as the return value, which is unique in all the entire web application all of the web applications. (Try the title out, the source code automatically generated by ASP.NET can go to the system disk: /Windows/Microsoft.Net/framework/v1.0.3705/temporary asp.net file below to find it), this unique hash value is in order A tag is generated in ViewState so that this viewState only applies to the corresponding page. Second is the object of the Control.saveViewStateRecursive method recursively saves the ViewState of the page control tree, which is the real viewstate data. The current page requires a list of POSTBACK controlled names.
Analyze the configuration of the page of the page, let's see the implementation of Control's ViewState. ViewState is an attribute of the system.web.ui.control class. This property is system.web.ui.statebag, which contains the implementation of the ViewState data structure. In fact, its internal is a Hash table. Save and retrieve data through the key value. Then how the server control is saved? We know that all server controls are derived from system.web.ui.control, so they all have ViewState properties, in the Control inside, define two protected virtual methods: protected virtual object saveviewstate () and protected virtual void LoadViewState (Object SavedState) These two methods are to derive and read their own ViewState to the child control. For example, we have a controlled control, saved a string in ViewState, then our method is roughly like this : Protected version () {Object [] stats = new object [2]; states [0] = base.saveViewState (); // Remember to save the VIEWSTATE STATES [1] = "Hello, I'm Timmy ! "; // Save our own return stats; // Return to the re-packaged save object} Get: protected override void loadviewstate (Object SavedState) // The savedState here is the Object array of returna when we save { Object [] States = (Object []) SavedState; Base.LoadViewState (States [0]); // Put the parent class's data to himself to resolve string mydata = (String) States [1]; // Get our own Data} We can save them in your own way, not necessarily to use arrays above, in fact, we can use any support for serialized objects, parent classes don't care how to save the subclasses, we only need to be in Save Use the same way as LOAD and pass the correct data to the parent method. In addition, there is a problem that what we use Control's viewState is key-value such as Key-Value, how is it saved? In fact, there is a class called Pair, huh, this and Triplet is almost two objects. When StateBag is saved, First will store arrays of all KEY values, and Second stores arrays of all Value.
To now, we understand how the viewState serits and saves the client, and also understands how the control saves your own ViewState, how is the two combined?
That is, how is the control tree of the entire page to save and read?
There are two internal in the Internal Control method: internal object SaveViewStateRecursive (); internal void LoadRecursive (); these two methods called by System.Web.UI.Page, Page SavePageViewState method is called at the end of Render, SavePageViewState method The Control's SaveViewStateRecursive () method is called by recursing each Control.Controls's SaveViewStateRecursive method to save the ViewState of all controls in the control tree. Here, a smart friend is asking, since SaveViewStateRecursive is a method of recursive call saving, then what is the use of the SaveViewState () method we wrote? We know that Control.Controls may have a lot, and our SaveViewState () only saves the data of the current control, without recording the structure of the control tree, then if we recursively savestate () method to save the data, then the control tree The structure will be lost. When LOAD is still restored, it is actually roughly code in the SaveViewStateRecursive method: [1] Get the control yourself "[2] cyclic sub-control {Definition two A dynamic array, a save control index, a save recursive sub-control SaveViewStateRecursive method returned} [3] Defines a Triplet (Oh, this thing appears) [4] first Save this control ViewState [5] SECOND Save the Sub-control index [6] THIRD Save the return value of the 子 子 控 SaveViewStateRecursive method [7] Returns Triplet to save the viewState and control tree of the entire control tree, the structure of the structure LOAD is similar to Save, just to LOAD, will The index of the child control is obtained in SaveDState to sequentially reciprocate the LoadRecursive () method of the child control, so that the correct data is transmitted to the child control.
Here, ViewState's implementation we will roughly understand, and finally draw some conclusions: 1. ViewState is stored in the client, so it will reduce the burden of the server, is a better way of saving data. 2. Because of the limitations of ViewState itself, only the objects that can be serialized, and it is best not to put too much thing, save the province, so as not to slow down the transmission, and the burden of the aggravation of the server. 3, we can get the value in ViewState through very simple way, we have discussed some, although not written out of the parsed code, but use Losformatter to get the object after viewstate, then resolve It is easy to be confident; so the viewState is still more poor, it is recommended not to store comparison confidential and sensitive information, although viewState can be encrypted, but because ViewState is saved on the client, there is security in security. 4, actually from the technical perspective, viewState does not have any new intentions, but the design of the server control is still very clever. Finally, in my personal point of view, I think the appearance of ViewState has greatly reduced the burden of the programmer, but to see the essence of ViewState, reasonable application. There are many problems in a hurry, I also hope that everyone will give more advice, please advise!