Search...

Friday, February 17, 2012

Detect refresh and redirect to error page in Asp.Net


*********************************************************************************

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Detect refresh and redirect to error page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <h1>Do not refresh this page</h1>
    </div>
    </form>
</body>
</html>

*********************************************************************************

using System;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Session["CheckRefresh"] == null)
                Session["CheckRefresh"] = Server.UrlDecode(System.DateTime.Now.ToString());
            else
                Response.Redirect("ErrorPage.htm");
        }
        else
            CheckRefresh();
    }

    private void CheckRefresh()
    {

        if (Session["CheckRefresh"].ToString().Equals(ViewState["CheckRefresh"].ToString()))
        {
            Session["CheckRefresh"] = Server.UrlDecode(System.DateTime.Now.ToString());
        }
        else
            Response.Redirect("ErrorPage.htm");
    }

    protected void Page_PreRender(object sender, EventArgs e)
    {
        ViewState["CheckRefresh"] = Session[" CheckRefresh "];
    }
}

No comments: