ASP.NET : ViewState解析
ASP.NET 的ViewState是使用Base64的字符串保存在一个隐藏域中的。下面通过一个例子来解析它们
1. 页面
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApp._Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:GridView ID="gv" runat="server" AllowPaging="true" AllowSorting="true" PageSize="5" onpageindexchanging="gv_PageIndexChanging"></asp:GridView> </div> </form> </body> </html>
2. 页面代码
using System; using System.Web.UI; using System.Web.UI.WebControls; using System.IO; using System.Text; namespace WebApp { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { DataBind(); } } public override void DataBind() { //1. 最传统的做法,直接在页面中处理业务逻辑 DirectoryInfo dir = new DirectoryInfo("e:\\temp"); gv.DataSource = dir.GetFiles(); gv.DataBind(); //2. 通过分层来实现业务逻辑的隔离 //localhost.Service1SoapClient proxy = new WebApp.localhost.Service1SoapClient(); //gv.DataSource = proxy.GetFiles(); //gv.DataBind(); } protected void gv_PageIndexChanging(object sender, GridViewPageEventArgs e) { gv.PageIndex = e.NewPageIndex; DataBind(); } protected override void SavePageStateToPersistenceMedium(object viewState) { // 调用基类的方法,完成基本操作 base.SavePageStateToPersistenceMedium(viewState); // 获取ViewState的Base64值 LosFormatter format = new LosFormatter(); StringWriter writer = new StringWriter(); format.Serialize(writer, viewState); string vsRaw = writer.ToString(); Response.Write("ViewState Raw: " + Server.HtmlEncode(vsRaw)); Response.Write("<br /><br />"); // 解析内容 byte[] buffer = Convert.FromBase64String(vsRaw); string vsText = Encoding.ASCII.GetString(buffer); Response.Write("ViewState Text: " + Server.HtmlEncode(vsText)); } } }
3. 测试效果