首页 > 编程 > .NET > 正文

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

2024-07-10 13:11:42
字体:
来源:转载
供稿:网友

  在 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 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

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表