使用正則Regex來移除網頁的EnableViewState實現思路及代碼

來源:互聯網
上載者:User

當你建立好一個網頁時,什麼都沒有寫,就可以運行,然後查看來源程式(View Source),就會看到下面一段。

此刻,也許你會想起,在網頁有一個屬性EnableViewState,可設為False,但似乎不見效果。

其實網頁有ViewState並不是壞事,但有時我們不需要它。怎樣辦?
首先回過頭來,看第一幅圖片,第12行代碼,即高亮部分,是我們想移掉的部分。我們可以使用正則,然後網頁重新Render,就可把它拿掉。

在.aspx.cs 或.aspx.vb引用namespace:

複製代碼 代碼如下:using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;

接下來,重寫Render()方法。複製代碼 代碼如下:protected override void Render(HtmlTextWriter writer)
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter hWriter = new HtmlTextWriter(sw);
base.Render(hWriter);
string html = sb.ToString();
html = Regex.Replace(html, "<input[^>]*id=\"(__VIEWSTATE)\"[^>]*>", string.Empty, RegexOptions.IgnoreCase);
writer.Write(html);
}

當然,上面只是針對單個網頁,如果你想要多個網頁移除ViewState時,你可以寫在一個BasePage基類,需要實現的網頁,再繼承這個BasePage.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.