我是asp.net mvc
中的新人,我需要检测用户的视图页面刷新并为此目的做一些事情阅读:
asp.net mvc - Detecting page refresh
for define action filter右键单击controller文件夹并添加RefreshDetectFilter
class:
namespace StoreProject.Controllers
{
public class RefreshDetectFilter : IActionFilter
{
public void OnActionExecuting(ActionExecutingContext filterContext)
{
var cookie = filterContext.HttpContext.Request.Cookies["RefreshFilter"];
filterContext.RouteData.Values["IsRefreshed"] = cookie != null &&
cookie.Value == filterContext.HttpContext.Request.Url.ToString();
}
public void OnActionExecuted(ActionExecutedContext filterContext)
{
filterContext.HttpContext.Response.SetCookie(new HttpCookie("RefreshFilter", filterContext.HttpContext.Request.Url.ToString()));
}
}
}
并以Global.asax
注册,以这种方式:
GlobalFilters.Filters.Add(new RefreshDetectFilter());
在我的行动中想要使用该代码的动作过滤器:
if (RouteData.Values["IsRefreshed"] == true)
{
// page has been refreshed.
}
答案 0 :(得分:4)
当您从RouteData.Values
中读取值时,您将获得Object
而不是bool
。在执行检查之前,您需要转换为适当的类型。
您还无需检查与true
的平等,因为该值已为true
或false
:
if ((bool) RouteData.Values["IsRefreshed"])
{
}