2017-09-01 51 views
0

我使用這個代碼,以確定我的頁面刷新,但它總是回來在我的控制器是真正刷新檢測過濾器始終是真實的

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())); 
    } 
} 

我有屬性和檢查

[RefreshDetectFilter] 
public class UserController : Controller 

的操作方法

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

回答

0

我懷疑你是不是在請求中的Cookie設置得足夠早它有什麼作用。每個MSDN

您必須在ASP.NET頁面呈現給客戶端之前創建cookie。例如,您可以在Page_Load事件處理程序中寫入Cookie,但不能在Page_Unload事件處理程序中寫入。有關頁面生命週期的更多信息,請參見ASP.NET Page Life Cycle Overview

儘管如此,如果你看一下MVC life cycle overview,動作過濾事件真的不排隊與ASP.NET頁面事件所以很難說沒有一些試驗。不過,我懷疑你需要做的:

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())); 
    } 
} 

注:如果設置一個路由值這種方式,它最終將成爲其在視圖生成的每個URL的查詢字符串參數。很難說這是你的意圖還是不希望的副作用。