Friday, April 9, 2010

How to Detect Refresh in ASP.Net web forms

I use this code to detect refresh in asp.net web forms. This methods uses Session.

I create a static class
public static class RefreshDetectionTools
{
#region Constants
private const string KEY_REF_DEC_HID = "RefDecHid";
private const string KEY_REF_DEC_STAMP = "RefDecStamp";
#endregion

#region Methods
public static bool IsPageRefresh()
{
Page page = HttpContext.Current.CurrentHandler as Page;

string val = HttpContext.Current.Request[KEY_REF_DEC_HID];

if ((val == null) || (val.Length == 0)) return false;

string stamp = HttpContext.Current.Session[KEY_REF_DEC_STAMP] as string;
if (stamp == null)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Write("Session Expired.");
HttpContext.Current.Response.End();
}
if (stamp != val)
return true;
else
return false;
}
///
/// You need to call this method in Page_PreRender to make the
/// refresh detection working
///

public static void StampRefreshDetection()
{
Page page = HttpContext.Current.CurrentHandler as Page;

string stamp = HttpContext.Current.Server.UrlEncode(DateTime.Now.ToString());

HttpContext.Current.Session[KEY_REF_DEC_STAMP] = stamp;

page.ClientScript.RegisterHiddenField(KEY_REF_DEC_HID, stamp);
}
#endregion
}

Then in any asp.net web form that needs to detect refresh, in Page_PreRender handler we need to call RefreshDetectionTools.StampRefreshDetection() and then any where you want to detect the refresh, we check StampRefreshDetection.IsPageRefresh()

Hope you enjoy, Cheers

0 comments:

Post a Comment