Asp. NET prevents page refreshes in two ways

Source: Internet
Author: User
Tags bool md5 md5 encryption

  This article is mainly on the asp.net to prevent the page to refresh the two solutions to the detailed analysis of the introduction, the need for friends can come to the reference, I hope to help you all

Method has two, summarized as follows:    first method:  directly in CS code to knock:  Response.Buffer = true;  Response.ExpiresAbsolute = DateTime.Now.AddSeconds ( -1);  Response.Expires = 0;  Response.CacheControl = "No-cache";    When someone wants to push back the page has expired, the effect is up to     The second method:  submitoncepage: Resolve refresh the page caused by duplicate data submission problem (online data)     When a Web page that performs a postback operation is refreshed, the browser will have the prompt "do not resend the information, cannot refresh the Web page", and if you have just performed the action of inserting a new record into the database, the result of the point [retry] is inserting two duplicate records, It has always been a solution to the current page after saving data, and recently found a new method.     Problem analysis     In the System.Web.UI.Page class, there is a ViewState attribute to hold the current view state of the page, and to observe the resulting HTML code for each ASPX page can be found by adding a hidden field named __viewstate to the page. The value is the current state of the page, and the value changes after each execution of postback, and the Refresh page does not change.     In this case, we can write the current viewstate to a session at the end of the page code execution, while the page is loaded to determine whether the session value is the same as the current ViewState equal (in fact, the session value is exactly the first state of the ViewState), if unequal, it is normal postback, if the same is the browser refresh, so, It is possible to prevent data duplication by nesting an if judgment outside of our data insertion code.     In fact, the problem has not been fully resolved, specifically, the session of the key value problem. Let's say we save the viewstate as this. session["Myviewstate"], if a user at the same time open two anti-refresh submission of the page is out of order, that the page URL set session key value? No, not yet.Because it is possible for a user to open the same page in two windows, you must define a unique session key value for each open page, and the key value can be saved with the current page instance, depending on how the viewstate is saved, We add a hidden field directly to the page to store the session key value.     by OOP80 and edward.net reminders, in order to minimize the session data consumption of server resources, the above scheme is adjusted slightly, will viewstate use MD5 encryption after the return of 32-bit string write session.     In addition, because this method generates additional session Occupancy server resources, use if you must keep the current page state, and then redirect directly to the current page when the data submission is complete without having to keep the current page state.     submitoncepage    Submitoncepage is written for the above analysis of a inherited from System.Web.UI.Page base class, need to prevent the refresh of repeated submissions from the base class page inheritance, the source code as follows:    codes are as follows: namespace mycontrol  { ///<summary> ///name:submitoncepage ///parent class:system.web.ui.page /// Description: Page extension class that resolves data recurrence problems caused by browser refreshes.  ///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 "; &nbsP _strsessionkey = System.Guid.NewGuid (). ToString ();  _strlastviewstate = string. empty; }    public bool isrefreshed  {  get  {  String str1 = Getsessincontent (); &nbsp ; _strlastviewstate = str1;  String str2 = this. Session[getsessinkey ()] as string;  bool Flag1 = (str1!= null) && (str2!= null) && (str1 = = str2); nbsp return flag1; } }    protected override void Render (System.Web.UI.HtmlTextWriter writer)   {& nbsp 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;&NBSp }  return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile (str, "MD5"); }    } }      test project     First compile the source code of the Submitoncepage class into a separate DLL and test it as follows:    1, create a new asp.net Web application;  2, add a DLL reference to the Submitoncepage class;  3, Add a Label control (LABEL1) and a button control (Button1) to WebForm1;  4, set Label1 text to 0;  5, double-click Button1 to go to the codebehind view;   6, modify the class WebForm1 parent class to Submitoncepage and add test code, the result is as follows:    code as follows: public class WebForm1: mycontrol.submitoncepage  {  protected System.Web.UI.WebControls.Label label1;  protected System.Web.UI.WebControls.Button button1;      #region Web Forms Designer generated code   override protected void OnInit (EventArgs e)   { // //CodeGen: This call is required for the ASP.net Web forms Designer.  //  InitializeComponent ();  base. OnInit (e); }   ///<summary> ///Designers support the required methods-do not use the Code Editor to modify  ///The content 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 Run, in the browser window several consecutive clicks Button1, and then refresh several pages, and then click a few button1;    8, go to the test project corresponding directory, Open the A.txt and b.txt files to see if (!this. isrefreshed) of the concrete effect.    
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.