网络编程 | 站长之家 | 网页制作 | 图形图象 | 操作系统 | 冲浪宝典 | 软件教学 | 网络办公 | 邮件系统 | 网络安全 | 认证考试 | 系统进程
Firefox | IE | Maxthon | 迅雷 | 电驴 | BitComet | FlashGet | QQ | QQ空间 | Vista | 输入法 | Ghost | Word | Excel | wps | Powerpoint
asp | .net | php | jsp | Sql | c# | Ajax | xml | Dreamweaver | FrontPages | Javascript | css | photoshop | fireworks | Flash | Cad | Discuz!
当前位置 > 网站建设学院 > 网络编程 > ASP.NET技巧
Tag:注入,存储过程,分页,安全,优化,xmlhttp,fso,jmail,application,session,防盗链,stream,无组件,组件,md5,乱码,缓存,加密,验证码,算法,cookies,ubb,正则表达式,水印,索引,日志,压缩,base64,url重写,上传,控件,Web.config,JDBC,函数,内存,PDF,迁移,结构,破解,编译,配置,进程,分词,IIS,Apache,Tomcat,phpmyadmin,Gzip,触发器,socket
网络编程:ASP教程,ASP.NET教程,PHP教程,JSP教程,C#教程,数据库,XML教程,Ajax,Java,Perl,Shell,VB教程,Delphi,C/C++教程,软件工程,J2EE/J2ME,移动开发
本月文章推荐
.ASP.NET设计中的性能优化问题.
.正则表达式提取数字.
..net2.0中使用SqlBulkCopy进行大.
.在ASP.NET中上传图片并生成缩略图.
.Web Service非Soap头(Session)身.
.使用ASP.NET 2.0中的ReportViewe.
.理解IIS7的用户和组.
.如何在web.config中建立公用的的.
.asp.net调用存储过程方法新解.
.手把手教你如何扩展GridView之个.
.如何在删除并重新安装 IIS 之后修.
.ASP.Net中自定义Http处理及应用之.
.repeater实现多列显示.
.使用.NET实现断点续传.
.用window.location.href实现刷新.
.ASP.NET中利用存储过程实现模糊查.
.Asp.net把UTF-8编码转换为GB2312.
.通过改善架构来提高 ASP.Net 应用.
.立即释放.net下的com组件.
.做个DataList 可分页的数据源.

ASP.NET小技巧:重写ViewState的存储目的地,以提高页面性能

发表日期:2006-2-27


在 ASP.NET 中,ViewState 因为在客户端的 HTML 里占据大量的空间,并随着页面的 PostBack 反复传递于网络中,一直为人垢病。但是实际上 ViewState 可以存储到数据库、缓存等任意地方,从而避免频繁将冗长的 base64 字符串发送到客户端。这样做不但可以显著提高性能(大幅度减少了网络传输的字节数),而且如果其中的内容也不会被轻易解密和破解。因此这个方法是很有用处的。
以下写了一个简单的例子,用缓存来作为 ViewState 存储目的地。至于缓存的 Key,文中给出的只是一个简单的写法,具体可以根据情况给出严密的方案。

代码大致演示如下:

<%@ Page language="c#" Codebehind="SaveViewStateToOther.aspx.cs" AutoEventWireup="false" Inherits="LinkedList.SaveViewStateToOther" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<html>
  <head>
    <title>SaveViewStateToOther</title>
    <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
    <meta name="CODE_LANGUAGE" Content="C#">
    <meta name=vs_defaultClientScript content="JavaScript">
    <meta name=vs_targetSchema content="http://schemas.microsoft.com/intellisense/ie5">
  </head>
  <body MS_POSITIONING="GridLayout">
   
    <form id="Form1" method="post" runat="server"><asp:DataGrid id=DataGrid1 style="Z-INDEX: 101; LEFT: 104px; POSITION: absolute; TOP: 72px" runat="server" BorderColor="#3366CC" BorderStyle="None" BorderWidth="1px" BackColor="White" CellPadding="4" PageSize="6" AllowPaging="True">
<selecteditemstyle font-bold="True" forecolor="#CCFF99" backcolor="#009999">
</SelectedItemStyle>

<itemstyle forecolor="#003399" backcolor="White">
</ItemStyle>

<headerstyle font-bold="True" forecolor="#CCCCFF" backcolor="#003399">
</HeaderStyle>

<footerstyle forecolor="#003399" backcolor="#99CCCC">
</FooterStyle>

<pagerstyle horizontalalign="Left" forecolor="#003399" backcolor="#99CCCC" pagebuttoncount="20" mode="NumericPages">
</PagerStyle>
</asp:DataGrid>

     </form>
   
  </body>
</html>

using System;
using System.Data;
using System.IO;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace LinkedList
{
    /// <summary>
    /// SaveViewStateToOther 的摘要说明。
    /// </summary>
    public class SaveViewStateToOther : Page
    {
        protected DataGrid DataGrid1;

        private void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
                Bind();
        }

        private void Bind()
        {
            DataTable table = new DataTable();
            table.Columns.Add("id", typeof (int));
            table.Columns.Add("name", typeof (string));

            for (int i = 0; i < 1000; i++)
            {
                DataRow row = table.NewRow();
                row["id"] = i;
                row["name"] = "student_" + i.ToString();
                table.Rows.Add(row);
            }
            DataGrid1.DataSource = table;
            DataGrid1.DataBind();
        }

        #region Web 窗体设计器生成的代码

        protected override void OnInit(EventArgs e)
        {
            InitializeComponent();
            base.OnInit(e);
        }

        private void InitializeComponent()
        {
            this.DataGrid1.PageIndexChanged += new System.Web.UI.WebControls.DataGridPageChangedEventHandler(this.DataGrid1_PageIndexChanged);
            this.Load += new System.EventHandler(this.Page_Load);

        }

        #endregion

        protected override void SavePageStateToPersistenceMedium(object viewState)
        {
            LosFormatter format = new LosFormatter();
            StringWriter writer = new StringWriter();
            format.Serialize(writer, viewState);
            string vsRaw = writer.ToString();
            byte[] buffer = Convert.FromBase64String(vsRaw);
            string vsText = Encoding.ASCII.GetString(buffer);

            object v = Cache[PageKey];
            if (v == null)
                Cache.Insert(PageKey, vsText);
            else
                Cache[PageKey] = vsText;
        }

        public string PageKey
        {
            get { return Session.SessionID + "_page_SaveViewStateToOther_aspx"; }
        }

        protected override object LoadPageStateFromPersistenceMedium()
        {
            object s = Cache[PageKey];
            if (s != null)
            {
                string state = s.ToString();
                byte[] buffer = Encoding.ASCII.GetBytes(state);
                string vsRaw = Convert.ToBase64String(buffer);
                LosFormatter formatter = new LosFormatter();
                return formatter.Deserialize(vsRaw);
            }
            return null;
        }

        private void DataGrid1_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
        {
            DataGrid1.CurrentPageIndex = e.NewPageIndex;
            Bind();
        }
    }
}
对于实际的应用,如果要决定在整个程序中应用此方案,则使用一个通用的页面基类,在其中实现此机制比较合适。

出处:木野狐 BLOG

上一篇:关于OpenSmtp邮件标题过长后出现乱码问题的解决 人气:6292
下一篇:ASP.NET: Custom AutoCompleteTextBox WebControl [With Source Code] 人气:7295
浏览全部ASP.NET的内容 Dreamweaver插件下载 网页广告代码 祝你圣诞节快乐 2009年新年快乐