打印本文 打印本文 关闭窗口 关闭窗口
Cutting Edge The ASP.NET View State
作者:武汉SEO闵涛  文章来源:敏韬网  点击数2646  更新时间:2009/4/23 10:46:58  文章录入:mintao  责任编辑:mintao
ernative storage schemes. The class contains a couple of protected virtual methods that the runtime uses to deserialize or serialize the view state. LoadPageStateFromPersistenceMedium is used to restore the view state at the beginning of the page lifecycle. By contrast, a method named SavePageStateToPersistenceMedium is used to persist the view state just before the page is rendered:
protected virtual void SavePageStateToPersistenceMedium
    (object viewState);
protected virtual object LoadPageStateFromPersistenceMedium();
Override both methods and you can load and save view state information to and from virtually any storage medium other than a hidden field. (Note that you cannot override only one method; you have to override both.) Since the methods are defined as protected members, the only way to redefine them is to create a new class that derives from Page. The following code gives you an idea of the default behavior of the loading method:
string m_viewState = Request.Form["__VIEWSTATE"];
LosFormatter m_formatter = new LosFormatter();
object viewStateBag = m_formatter.Deserialize(m_viewState);

   Notice that the object returned by the LosFormatter''''s Deserialize method is not the StateBag object that the programmers actually work with. What the Deserialize method returns is just one of the intermediate internal objects that I mentioned earlier. The structure of the page I''''m going to create is shown here:
public class ServerViewStatePage : Page 
{
  protected override object LoadPageStateFromPersistenceMedium() 
    { ... }
  protected override void SavePageStateToPersistenceMedium(object 
      viewState) { ... }
}

   The tasks accomplished by the SavePageStateToPersistenceMedium method are very easy to understand. The method takes the string as an argument, opens the output stream, and calls into the LosFormatter serializer:
protected override void SavePageStateToPersistenceMedium
    (object viewStateBag) 
{
    string file = GetFileName();
    StreamWriter sw = new StreamWriter(file);
    LosFormatter m_formatter = new LosFormatter();
    m_formatter.Serialize(sw, viewStateBag);            
    sw.Close();
    return;
}
In this code snippet the view state is saved in a server-side file. With minimal changes, you could save it to a database as well. How should you choose the name of the file to ensure that no conflicts arise? The view state is specific to a page request made within a particular session. So the session ID and the request URL are unique pieces of information that can be used to associate the request with the right file. Alternatively, you could give the view state file a randomly generated name and persist the file name in a custom hidden field within the page. Note that in this case you should create the hidden field manually and not rely on the __VIEWSTATE field because in overriding the methods you alter the internal procedure that would have created it.
  The GetFileName function in the code I just showed gives the file a name according to the following pattern:
SessionID_URL.viewstate
Figure 8 shows some of these files created in a temporary directory. Note that for an ASP.NET application to create a local file you must give the ASP.NET account special permissions on a file or a folder. I suggest you create a new subfolder to contain all the view state files. Deleting files for expired sessions can be a bit tricky; you could write a Windows NT service that would periodically scavenge the temp directory to delete useless files. This would be better than just deleting files from within the Session_OnEnd event.
  The LoadPageStateFromPersistenceMedium method determines the name of the file to read from, extracts the Base64 string, and calls LosFormatter to deserialize (see Figure 9).
  To be able to create the view state on the server, a page only needs to inherit from the ServerViewStatePage class that I described a few code snippets earlier. Here''''s how it''''s done:
<% @Page Language="C#" Inherits="MsdnMag.ServerViewStatePage" %>

   Note, though, that session IDs (or any state mechanism) is also subject to sniffing and replay. So some of the same caveats discussed earlier apply here as well. Again, SSL is the best tool for ensuring the integrity of data on the wire. In addition, consider creating files outside the Web application space and give them random names. The actual file name can then be encoded and stored in a hidden field.

Conclusion
  The view state is a key element of an ASP.NET page because it is the primary means to persist the state of the Web server controls. Whenever the page posts back, the state is restored, updated using the current form parameters, then used to run the postback event handler. Normally, the view state is a hashed string encoded as Base64 and stored in a hidden field called __VIEWSTATE. In this way, the view state is not cached on the client, but simply transported back and forth with potential issues both for security and performance. As I said, you could keep the view state on the server, which requires only minimal coding. You will pay extra overhead because you''''re accessing a file off the disk or a database, but you''''ll be returning much slimmer pages while taking less of a security risk. Although in this column I considered persistent storage on the server (file or database), nothing would really prevent you from using the Cache object, thus combining server-side storage and speed of execution.

Send your questions and comments for Dino to cutting@microsoft.com.

Dino Esposito is an instructor and consultant based in Rome, Italy. Author of Building Web Solutions with ASP.NET and ADO.NET and Applied XML Programming for .NET, both from Microsoft Press, he spends his time teaching ASP.NET. Get in touch with Dino at dinoe@wintellect.com.

From the February 2003 issue of MSDN Magazine.
Get it at your local newsstand, or better yet, subscribe.

上一页  [1] [2] [3] 

打印本文 打印本文 关闭窗口 关闭窗口