Refresh detect filter is always true

735 views Asked by At

I'm using this code to determine if my page is refreshed but it's always coming back as true

public class RefreshDetectFilter : ActionFilterAttribute, IActionFilter
{
    //void  IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var cookie = filterContext.HttpContext.Request.Cookies["RefreshFilter"];
        filterContext.RouteData.Values["IsRefreshed"] = cookie != null &&
                                                            cookie.Value == filterContext.HttpContext.Request.Url.ToString();
    }

    //void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        filterContext.HttpContext.Response.SetCookie(new HttpCookie("RefreshFilter", filterContext.HttpContext.Request.Url.ToString()));
    }
}

in my controller I have the attribute and the check

[RefreshDetectFilter]
public class UserController : Controller

in the action method

if (Convert.ToBoolean(RouteData.Values["IsRefreshed"]) == true)
{
  // page has been refreshed.
}
1

There are 1 answers

0
NightOwl888 On

I suspect you are not setting the cookie early enough in the request for it to have any effect. Per MSDN:

You must create cookies before the ASP.NET page is rendered to the client. For example, you can write a cookie in a Page_Load event handler but not in a Page_Unload event handler. For more information on the page life cycle see ASP.NET Page Life Cycle Overview.

Although, if you look at the MVC life cycle overview, the action filter events don't really line up with ASP.NET page events so it is difficult to tell without some experimentation. That said, I suspect you need to do:

public class RefreshDetectFilter : ActionFilterAttribute, IActionFilter
{
    //void  IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var cookie = filterContext.HttpContext.Request.Cookies["RefreshFilter"];
        filterContext.RouteData.Values["IsRefreshed"] = cookie != null &&
                                                        cookie.Value == filterContext.HttpContext.Request.Url.ToString();

        filterContext.HttpContext.Response.SetCookie(new HttpCookie("RefreshFilter", filterContext.HttpContext.Request.Url.ToString()));
    }
}

NOTE: If you set a route value this way, it will end up as a query string parameter of every URL that is generated on the view. It is difficult to tell if that is your intention or an undesired side effect.