Detect browser refresh

时光毁灭记忆、已成空白 提交于 2019-12-01 03:24:40

问题


How can I find out if the user pressed F5 to refresh my page (Something like how SO implemented. If you refresh your page, the question counter is not increased). I have tested many code snippets mentioned in a dozen of tutorials, but none worked correctly.

To be more clear, suppose that i have an empty web form and would like to detect whether the user has pressed F5 in client-side (causing a refresh not submit) or not.

I can use session variables, but if the user navigates to another page of my site, and then comes back , I'd like to consider it as a new visit, not a refresh. so this is not a session-scope variable.

Thanks.

Update: The only workaround I could find was to inherit my pages from a base page, override the load method like below:

    public class PageBase : System.Web.UI.Page
{
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        this.Session["LastViewedPage"] = Request.RawUrl;
    }
}  

and in every page if I was interested to know if this is a refresh:

if (this.Session["LastViewedPage"].ToString() == Request.RawUrl)
{
    // This is a refresh!
}

回答1:


The only sure solution is to make a redirect to the same page , and here is a similar question: Post-Redirect-Get with ASP.NET

But there are also some other tricks, by adding some ticket on the page and see if this is the same or have change, see the full example and code at:

http://www.codeproject.com/Articles/68371/Detecting-Refresh-or-Postback-in-ASP-NET

and one more:

http://dotnetslackers.com/community/blogs/simoneb/archive/2007/01/06/Using-an-HttpModule-to-detect-page-refresh.aspx




回答2:


I run into this problem and use the following code. It works well for me.

bool isPageRefreshed = false;

protected void Page_Load(object sender, EventArgs args)
{
    if (!IsPostBack)
    {
        ViewState["ViewStateId"] = System.Guid.NewGuid().ToString();
        Session["SessionId"] = ViewState["ViewStateId"].ToString();
    }
    else
    {
        if (ViewState["ViewStateId"].ToString() != Session["SessionId"].ToString())
        {
            isPageRefreshed = true;
        }

        Session["SessionId"] = System.Guid.NewGuid().ToString();
        ViewState["ViewStateId"] = Session["SessionId"].ToString();
    } 
}


来源:https://stackoverflow.com/questions/6615403/detect-browser-refresh

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!