ASP. NET two solutions to prevent page refreshing

Source: Internet
Author: User

The method is summarized as follows:

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

When someone wants to press the back button, the page has expired and the effect is reached.

Method 2:
SubmitOncePage: solves the problem of repeated data submission caused by PAGE refreshing (online materials)

When the web page that has performed the postback operation is refreshed, the browser will prompt "cannot refresh the web page if no information is resending, if the operation just happened to insert a new record to the database, click [retry] to insert two duplicate records, in the past, we used to save the data and switch back to the current page. Recently, we found a new method.

Problem Analysis

In System. web. UI. in the Page class, the ViewState attribute is used to save the current view status of the Page. You can find the final html code generated by each aspx Page, in fact, a hidden field named _ VIEWSTATE is added to the page, and its value is the current status of the page. After each postback operation, the value changes, refreshing the page does not change.

In this case, we can write the current ViewState to a Session at the end of the page code execution, during page loading, the system checks whether the Session value is equal to the current ViewState value (in fact, the Session value happens to be in the previous state of ViewState). If the difference is not the same, it is a normal postback, if it is equal, the browser refresh. In this way, as long as an if judgment is nested outside the data insertion code, it can prevent repeated data submission.

In fact, the problem has not been completely solved, specifically the Session key value problem. Suppose we save ViewState as this. session ["myViewState"]. If a user opens two anti-Refresh submission pages at the same time, the Session key value is set for the page url? Still, because the user may open the same page in two windows, the unique Session key value must be defined for each page opened, this key value can be saved along with the current page instance. For more information, see the ViewState storage method. We can add a hidden domain to the page to store the Session key value.

Oop80 and Edward. net reminder, in order to reduce the usage of Session data to server resources as much as possible, the above scheme is slightly adjusted to write the 32-bit string returned by ViewState encryption using md5 into the Session.

In addition, this method generates additional sessions to occupy server resources. Therefore, use this method when the current page status must be retained. If the current page status does not need to be retained, after the data is submitted, you can directly redirect to the current page.

SubmitOncePage

SubmitOncePage is a base class inherited from System. Web. UI. Page for the above analysis. It is necessary to prevent the Page that refresh the committed data from inheriting from this base class. The source code is as follows:
Copy codeThe Code is as follows:
Namespace myControl
{
/// <Summary>
/// Name: SubmitOncePage
/// Parent class: System. Web. UI. Page
/// Description: page extension class that solves the problem of repeated data submission caused by browser refreshing.
/// Example: if (! This. IsRefreshed)
///{
//// 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 Item

First, compile the source code of the SubmitOncePage class into a separate dll, and then perform the test as follows:

1. Create an asp.net web application;
2. Add the dll reference corresponding to the SubmitOncePage class;
3. Add a Label control (Label1) and a Button control (Button1) to webform1 );
4. Set Text of Label1 to 0;
5. Double-click Button1 To Go To The codebehind view;
6. Modify the parent class of WebForm1 as SubmitOncePage and add the test code. The result is as follows:
Copy codeThe Code is as follows:
Public class WebForm1: myControl. SubmitOncePage
{
Protected System. Web. UI. WebControls. Label Label1;
Protected System. Web. UI. WebControls. Button Button1;


# Code generated by region Web Form Designer
Override protected void OnInit (EventArgs e)
{
//
// CODEGEN: This call is required by the ASP. NET Web form designer.
//
InitializeComponent ();
Base. OnInit (e );
}

/// <Summary>
/// The designer supports the required methods-do not use the code editor to modify
/// Content of this method.
/// </Summary>
Private void InitializeComponent ()
{
This. Button1.Click + = new System. EventHandler (this. button#click );
}
# Endregion

Private void button#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. In the browser window, click Button1 several times consecutively, refresh the page several times, and then click Button1 several times;

8 bytes to the test project directory, open the.txt and B .txt files, you can see if (! This. IsRefreshed.

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.