Summary of two solutions to prevent page refreshes

  • 2020-10-07 18:37:45
  • OfStack

There are two methods, which are summarized as follows:

Method 1:
Type directly into the CS code:
Response.Buffer = true;
Response.ExpiresAbsolute = DateTime.Now.AddSeconds(-1);
Response.Expires = 0;
Response.CacheControl = "no-cache";

When someone tries to click back the page is out of date and the effect is achieved

Method 2:
SubmitOncePage: Solve the problem of duplicate data submission caused by refreshing the page (online materials)

Out postback operation web when refresh the page, the browser will have a "not to send information, it is unable to refresh the web page, if just after just the operation of the new record is inserted into the database 1, point [retry] as a result of the insert two duplicate records, 1 straight is used after save the data back to the current page solution, has recently found a new way.

Problem analysis

In System. Web. UI. Page class, one called ViewState attributes in order to save the page the current view of the state, observe each aspx page the resulting html code can be found that is added to the page 1 is called __VIEWSTATE hidden field, its value value is the current state of the page, after executing each postback the value values will change, and refresh the page will not change.

Aimed at this situation, we can at the end of the page code execution of the current ViewState wrote 1 Session, whereas when the page is loaded to judge whether the Session value equals the current ViewState (Session value is the former ViewState 1 state), if the range, it is normal postback, if is equal to the browser refresh, so that 1 to, as long as the outside our data into code nested 1 if judgment can achieve the goal of prevent data repeat submitted.

In fact, the problem has not been completely solved here, specifically the key value problem of Session. Suppose we save ViewState as ES52en.Session ["myViewState"]. If one user opens two anti-refresh submission pages at the same time, what if we set the key value of Session for the page's url? It still doesn't work, because the user may open the same page in two Windows, so it is necessary to define the only key value of Session for each page opened, and the key value can be saved from the current page instance 1. Refer to the saving mode of ViewState, we can directly add a hidden field to the page to store the key value of Session.

After the reminder of oop80 and ES63en.Net, in order to reduce the amount of Session data on the server resources as far as possible, the above scheme is slightly adjusted, and the 32-bit string returned by ViewState after encryption by md5 is written into Session.

In addition, since this method will generate additional Session to consume server resources, use it if you must retain the current page state, or if you do not, redirect to the current page directly after you complete the data submission.

SubmitOncePage

SubmitOncePage is written on the above analysis one inherited from System. Web. UI. Page base class, the need to prevent the page refresh repeat submit data from the base class inheritance, source code is as follows:


namespace myControl 
{ 
/// <summary> 
///  Name: SubmitOncePage 
///  The parent class: System.Web.UI.Page 
///  Description: Solves the problem of duplicate data submission caused by browser refresh page Extension classes.  
///  Example: if (!this.IsRefreshed) 
///{ 
///// Specific code  
///} 
/// </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"); 
} 

} 
} 

Test project

First compile the source code of the SubmitOncePage class into a separate dll, and then test it. The steps are as follows:

1. Create a new ES91en. net web application;
2. Add dll reference corresponding to SubmitOncePage class;
3. Add 1 Label control (Label1) and 1 Button control (Button1) to webform1;
4. Set Text of Label1 to 0;
5. Double-click Button1 to go to codebehind view;
6. Modify the parent class of WebForm1 as SubmitOncePage and add the test code. The results are as follows:


public class WebForm1 : myControl.SubmitOncePage 
{ 
protected System.Web.UI.WebControls.Label Label1; 
protected System.Web.UI.WebControls.Button Button1; 

#region Web  Code generated by the forms designer  
override protected void OnInit(EventArgs e) 
{ 
// 
// CODEGEN:  The call is  ASP.NET Web  Required by the Forms designer.  
// 
InitializeComponent(); 
base.OnInit(e); 
} 
/// <summary> 
///  The designer supports the required methods  -  Do not modify using the code editor  
///  The contents of this method.  
/// </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. Press F5 to run, click Button1 in the browser window for several times in a row, then refresh the page for several times and click Button1 again;

8. Go to the corresponding directory of the test project, open a. txt and ES122en. txt file, and you will see if (! this. IsRefreshed).


Related articles: