刷新页面防止重复提交

using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

/// <summary>
///BasePage 的摘要说明
/// </summary>
public class BasePage : System.Web.UI.Page
{
    private static string PAGE_REFRESH_TICKET_KEY = "__PageRefreshTicketKey";
    private string PAGE_SESSION_REFRESH_TICKET_KEY = "__PageSessionRefreshTicketKey";

    /// <summary>
    /// 判断是否是PostBack
    /// </summary>
    /// <returns></returns>
    protected override System.Collections.Specialized.NameValueCollection DeterminePostBackMode()
    {
        //如果是通过"刷新"提交的后台,将页面强行设置成非PostBack模式,以实现刷新以重新的访问页面的形式进行
        if (IsRefreshed)
        {
            return null;
        }
        return base.DeterminePostBackMode();
    }

    protected override void OnPreRenderComplete(EventArgs e)
    {
        SynchroRefreshTicket();
        base.OnPreRenderComplete(e);
    }

    /// <summary>
    /// 同步页面和后台Session的票据
    /// </summary>
    private void SynchroRefreshTicket()
    {
        if (!Page.IsPostBack)
        {
            string strTicket = Guid.NewGuid().ToString();
            ClientScript.RegisterHiddenField(PAGE_REFRESH_TICKET_KEY, strTicket);
            ClientScript.RegisterHiddenField(PAGE_SESSION_REFRESH_TICKET_KEY, strTicket);
            Session[strTicket] = strTicket;
        }
        else
        {
            string strTicket = Guid.NewGuid().ToString();
            ClientScript.RegisterHiddenField(PAGE_REFRESH_TICKET_KEY, strTicket);
            ClientScript.RegisterHiddenField(PAGE_SESSION_REFRESH_TICKET_KEY, Request.Form[PAGE_SESSION_REFRESH_TICKET_KEY]);
            Session[Request.Form[PAGE_SESSION_REFRESH_TICKET_KEY]] = strTicket;
        }
    }


    /// <summary>
    /// 比较HiddenField的票据和Session中存储的票据是否相同,如果不相同则为通过刷新的方式进行的提交
    /// </summary>
    protected bool IsRefreshed
    {
        get
        {
            if (string.Equals(Request.Form.Get(PAGE_REFRESH_TICKET_KEY), Session[Request.Form.Get(PAGE_SESSION_REFRESH_TICKET_KEY)]))
            {
                return false;
            }
            else
            {
                return true;
            }
        }
    }
}
原文地址:https://www.cnblogs.com/daixingqing/p/2768430.html