Identify Page Refresh in ASP.NET MVC

Identify Page Refresh in ASP.NET MVC

Let say in an online test application with the counter on the top, refreshing the page will start the counter again leading the users to read all the questions again and again.

-One of the solutions to the problem is disable F5 Button using javascript. But there are other options available too for refreshing browser like Right Click select refresh option, click on browser refresh icon. Hence in these cases javascript will not work. So the best option is to use ActionFilter.

– Make an action filter as below:

public class FindRefreshDetectFilter : ActionFilterAttribute,IActionFilter

{

public override void OnActionExecuting(ActionExecutingContext filterContext)

{

var cookie = filterContext.HttpContext.Request.Cookies[“FindRefreshFilter”];

filterContext.RouteData.Values[“IsRefreshed”] = cookie != null &&

cookie.Value == filterContext.HttpContext.Request.Url.ToString();

if ((bool)filterContext.RouteData.Values[“IsRefreshed”])

{

filterContext.Result = new RedirectResult(“~/Online/SignIn”);

}

}

public override void OnActionExecuted(ActionExecutedContext filterContext)

{

filterContext.HttpContext.Response.SetCookie(new HttpCookie(“FindRefreshFilter”,   filterContext.HttpContext.Request.Url.ToString()));

}

}

– Check the value in Controller as :

[FindRefreshDetectFilter]

public ActionResult Test()

{

if ((bool)RouteData.Values[“IsRefreshed”] == true)

return View(“PageRefreshed”);

else

return View();

}

CONCLUSION:

The above Action Filter based solution for detecting page refresh in MVC is not ultimate solution but highly flexible as we can add some more functionality and features according to our need.

Tags:
  • page refresh in asp .net,
  • Page Refresh in ASP.NET MVC,
  • Leave a Reply