程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> ASP.NET >> ASP.NET基礎 >> ASP.NET防止頁面刷新的兩種解決方法小結

ASP.NET防止頁面刷新的兩種解決方法小結

編輯:ASP.NET基礎

方法有二,總結如下:

第一方法:
直接在CS代碼裡敲:
Response.Buffer = true;
Response.ExpiresAbsolute = DateTime.Now.AddSeconds(-1);
Response.Expires = 0;
Response.CacheControl = "no-cache";

當有人想按後退時頁面已過期,效果就達到了

第二方法:
SubmitOncePage:解決刷新頁面造成的數據重復提交問題(網上資料)

執行過postback操作的web頁面在刷新的時候,浏覽器會有“不重新發送信息,則無法刷新網頁”的提示,若剛剛執行的恰好是往數據庫插入一條新記錄的操作,點[重試]的結果是插入了兩條重復的記錄,以前一直是用保存數據後重新轉向當前頁面的方法解決,最近又找到了一個新的方法。

問題分析

在System.Web.UI.Page類中,有一個名為ViewState屬性用以保存頁面的當前視圖狀態,觀察每個aspx頁面最終生成的html代碼可以發現,其實就是向頁面添加了一個名為__VIEWSTATE的隱藏域,其value值就是頁面的當前狀態,每次執行postback過後,該 value值都會發生變化,而刷新頁面則不會改變。

針對這種情況,我們可以在頁面代碼執行的末尾將當前的ViewState寫到一個Session中,而在頁面加載時則判斷該Session值是否與當前 ViewState相等(其實Session值恰好是ViewState的前一狀態),若不等,則是正常的postback,若是相等則是浏覽器刷新,這樣一來,只要在我們的數據插入代碼外嵌套一個if判斷就可以達到防止數據重復提交的目的了。

其實到這裡問題還沒有完全解決,具體說來就是Session的鍵值問題。假設我們將ViewState保存為 this.Session["myViewState"],如果一個用戶同時打開兩個防刷新提交的頁面就亂套了,那針對頁面的url設置Session的鍵值呢?還是不行,因為用戶有可能在兩個窗口中打開同一頁面,所以必須為每次打開的頁面定義唯一的Session鍵值,並且該鍵值可以隨當前頁面實例一起保存,參考ViewState的保存方式,我們直接向頁面添加一個隱藏域專門存放Session鍵值就可以了。

經oop80和Edward.Net的提醒,為了盡可能地降低Session數據對服務器資源的占用量,現將上述方案略做調整,將ViewState利用md5加密後返回的32位字符串寫入Session。

另外,由於本方法會生成額外的Session占用服務器資源,所以請在必須保留當前頁面狀態的情況下使用,若無需保留當前頁面狀態,則在完成數據提交後直接重定向到當前頁面即可。

SubmitOncePage

SubmitOncePage是針對上述分析寫的一個繼承自System.Web.UI.Page的基類,需要防止刷新重復提交數據的頁面從該基類繼承,源碼如下:
復制代碼 代碼如下:
namespace myControl
{
/// <summary>
/// 名稱:SubmitOncePage
/// 父類:System.Web.UI.Page
/// 描述:解決浏覽器刷新造成的數據重復提交問題的page擴展類。
/// 示例:if (!this.IsRefreshed)
///{
/////具體代碼
///}
/// </summary>
public class SubmitOncePage:System.Web.UI.Page
{
private string _strSessionKey;
private string _hiddenfieldName;
private string _strLastViewstate;

public SubmitOncePage()
{
_hiddenfieldName = "__LastVIEWSTATE_SessionKey";
_strSessionKey = System.Guid.NewGuid().ToString();
_strLastViewstate = string.Empty;
}

public bool IsRefreshed
{
get
{
string str1 = GetSessinContent();
_strLastViewstate = str1;
string str2 = this.Session[GetSessinKey()] as string;
bool flag1 = (str1 != null) && (str2 != null) && (str1 == str2);
return flag1;
}
}

protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
string str = GetSessinKey();
this.Session[str] = _strLastViewstate;
this.RegisterHiddenField(_hiddenfieldName, str);
base.Render(writer);
}


private string GetSessinKey()
{
string str = this.Request.Form[_hiddenfieldName];
return (str == null) ? _strSessionKey : str;
}

private string GetSessinContent() {
string str = this.Request.Form["__VIEWSTATE"];
if (str == null) {
return null;
}
return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5");
}

}
}

測試項目

首先將SubmitOncePage類的源碼編譯成一個單獨的dll,然後進行測試,步驟如下:

1、新建一個asp.net web應用程序;
2、添加SubmitOncePage類對應的dll引用;
3、給webform1添加一個Label控件(Label1)和一個Button控件(Button1);
4、設置Label1的Text為0;
5、雙擊Button1轉到codebehind視圖;
6、修改類WebForm1的父類為SubmitOncePage並添加測試代碼,結果如下:
復制代碼 代碼如下:
public class WebForm1 : myControl.SubmitOncePage
{
protected System.Web.UI.WebControls.Label Label1;
protected System.Web.UI.WebControls.Button Button1;


#region Web 窗體設計器生成的代碼
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 該調用是 ASP.NET Web 窗體設計器所必需的。
//
InitializeComponent();
base.OnInit(e);
}

/// <summary>
/// 設計器支持所需的方法 - 不要使用代碼編輯器修改
/// 此方法的內容。
/// </summary>
private void InitializeComponent()
{
this.Button1.Click += new System.EventHandler(this.Button1_Click);
}
#endregion

private void Button1_Click(object sender, System.EventArgs e)
{
int i=int.Parse(Label1.Text)+1;
Label1.Text = i.ToString();
if (!this.IsRefreshed)
{
WriteFile("a.txt", i.ToString());
}
WriteFile("b.txt", i.ToString()); 


}

private void WriteFile(string strFileName,string strContent)
{
string str = this.Server.MapPath(strFileName); 
System.IO.StreamWriter sw = System.IO.File.AppendText(str);
sw.WriteLine(strContent);
sw.Flush();
sw.Close(); 
}
}

7、按F5運行,在浏覽器窗口中連續點擊幾次Button1,然後刷新幾次頁面,再點擊幾次Button1;

8、轉到測試項目對應目錄下,打開a.txt和b.txt文件,可看到if (!this.IsRefreshed) 的具體效果。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved