Adr*_*oRR 2 asp.net-mvc tempdata browser-refresh
我理解StackOverflow上有关于这个问题的类似问题,但没有一个能解决我的问题,所以我正在创建一个新问题.
正如标题所说,我想检测用户何时刷新页面.我有一个页面,我保存一些用户在其上完成的日志信息(添加,删除或编辑项目).此日志只能在用户离开页面时保存,而不能通过刷新保存.
我尝试了下面的示例来检测它是刷新还是新请求:
public ActionResult Index()
{
var Model = new Database().GetLogInfo();
var state = TempData["refresh"];
if(state == null)
{
//This is a mock structure
Model.SaveLog(params);
}
TempData["refresh"] = true; //it can be anything here
return View();
}
Run Code Online (Sandbox Code Playgroud)
考虑到它是一个TempData它应该在我的下一个行动到期.但是,由于某种原因,它在整个应用程序中存活了下来.根据这个博客,它应该在我随后的请求到期(除非我不理解的东西).即使我从我的应用程序注销并再次登录,我的TempData仍然存在.
我一直在考虑使用javascript函数onbeforeunload对一些动作进行AJAX调用,但我再一次不得不依赖TempData或以某种方式持久保存这个刷新信息.有小费吗?
你可以使用ActionFilter看起来像这样的东西:
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()));
}
}
Run Code Online (Sandbox Code Playgroud)
注册global.asax.然后你可以在控制器中执行此操作:
if (RouteData.Values["IsRefreshed"] == true)
{
// page has been refreshed.
}
Run Code Online (Sandbox Code Playgroud)
您可能希望改进检测以检查所使用的HTTP方法(因为POST和GET URL看起来相同).请注意,它使用cookie进行检测.