Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

How to prevent Re-Post action caused by pressing browser's Refresh button

0.00/5 (No votes)
5 Feb 2012 1  
Simple Web User Control prevents unexpected action caused by Refresh Button

The Problem


When a user presses the Browser's Refresh button (Or F5/Ctrl+R etc.) the browser resends the last request data to the server.
This action causes an Unexpected Re-Post action (if there was one).
In some cases, it can be very problematic (For example, in shopping website when the user clicks on "Add to Cart" button and then presses the Refresh button - the item will be added twice !!!)

The solution


We will store a unique code (in my case Guid) on both client and server and compare them on every request action. If the two codes are not equal, the action will be canceled and the page will reload ('GET' method).

Add Web User Control with this code:

Markup

Add a hidden field to hold client code
ASP.NET
<asp:HiddenField runat="server" ID="_repostcheckcode" />

Code behind


C#
protected void Page_Load(object sender, EventArgs e)
{
    CancelUnexpectedRePost();
}

private void CancelUnexpectedRePost()
{
    string clientCode = _repostcheckcode.Value;

    //Get Server Code from session (Or Empty if null)
    string serverCode = Session["_repostcheckcode"] as string  ?? "";

    if (!IsPostBack || clientCode.Equals(serverCode))
    {
        //Codes are equals - The action was initiated by the user
        //Save new code (Can use simple counter instead Guid)
        string code = Guid.NewGuid().ToString();
        _repostcheckcode.Value = code;
        Session["_repostcheckcode"] = code;
    }
    else
    {
        //Unexpected action - caused by F5 (Refresh) button
        Response.Redirect(Request.Url.AbsoluteUri);
    }
}


Now you can drag the User Control to every page you want to handle that problem, or you can drag it to your Master Page to handle the problem in the entire site.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here