Ing*_*mar 7 asp.net asp.net-mvc
我正在使用ASP.NET MVC(最新版本).
想象一下有两页:
第1页:"输入数据">>第2页:"谢谢"
提交Page-1后,您将被重定向到Page-2.
我的目标:当你进入Page-2后,当你点击浏览器的后退按钮时,我想确保你不能回到Page-1.相反,我希望你留在Page-2(或每次按下后退按钮时被推到Page-2).
我尝试过各种各样的事情.以下只是一些简化的伪代码......
[NoBrowserCache]
public ActionResult Page1(int userId)
{
var user = GetUserFromDb(userId);
if (user.HasAlreadySubmittedPage1InThePast)
{
// forward to page 2
return RedirectToAction("Page2", routeValues: new { userId = userId });
}
var model = new Page1Model();
return View("Page1", model);
}
[NoBrowserCache]
[HttpPost]
public ActionResult Page1(Page1Model model)
{
var user = GetUserFromDb(model.UserId);
if (user.HasAlreadySubmittedPage1InThePast)
{
// forward to page 2
return RedirectToAction("Page2", routeValues: new { userId = model.UserId });
}
// Save posted data to the db
// ...
return RedirectToAction("Page2", routeValues: new { userId = model.UserId });
}
public class NoBrowserCache : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// Haha ... tried everything I found on the web here:
// Make sure the requested page is not put in the browser cache.
filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
filterContext.HttpContext.Response.Cache.SetNoStore();
filterContext.HttpContext.Response.Cache.AppendCacheExtension("no-cache");
filterContext.HttpContext.Response.Cache.SetExpires(DateTime.Now);
filterContext.HttpContext.Response.Expires = 0;
}
}
Run Code Online (Sandbox Code Playgroud)
如果我每次点击后退按钮时都能确保将请求发送到服务器.但是现在,单击后退按钮只是从浏览器的缓存中拉出Page-1而不向服务器发送请求.所以目前,我没有机会通过服务器方式将您转发到Page-2.
任何想法或建议?
多谢你们!
顺便说一句:没有涉及登录/身份验证.所以,我不能使用Session.Abandon()或类似的东西.如果可能的话,我宁愿使用一些基于服务器的代码而不是javascript.
编辑2017-5-12关注 @ grek40,我确保反查询语句最终出现在浏览器中.我因此从上面的C#代码中完全删除了[NoBrowserCache] -ActionFilterAttribute.相反,我在_Layout.cshtml的<head>部分添加了以下语句:
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">
Run Code Online (Sandbox Code Playgroud)
我确认这三行正在呈现给我的浏览器(使用浏览器的开发人员工具进行检查).但是,缓存仍然有效.我仍然可以在没有服务器请求的情况下向后移 使用Google Chrome v62,Firefox Quantum v57和Microsoft Edge v41(全部在Win10上)进行了测试.#
编辑2017-6-12 再次关注@ grek40的建议:尝试过期:0以及过期:-1.没有不同.我仍然无法管理,关闭浏览器的缓存.
最后我找到了解决方案。它基于 javascript,但非常简单。
我只需要将以下代码段添加到我的第 2 页(我不希望用户到达后离开的页面):
<script type="text/javascript">
$(document).ready(function () {
history.pushState({ page: 1 }, "title 1", "#nbb");
window.onhashchange = function (event) {
window.location.hash = "nbb";
};
});
Run Code Online (Sandbox Code Playgroud)
我在这里找到了这个:how to stop browser back button using javascript
感谢大家的支持。但是“我自己的”解决方案是唯一有效的解决方案。
| 归档时间: |
|
| 查看次数: |
3813 次 |
| 最近记录: |