C# 如何检测.net中的页面刷新
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11793588/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to detect page refresh in .net
提问by Srikanth
I have a Button_clickevent. While refreshing the page the previous Postbackevent is triggering again. How do I identify the page refresh event to prevent the Postbackaction?
我有一个Button_click活动。刷新页面时,上一个Postback事件再次触发。如何识别页面刷新事件以阻止该Postback操作?
I tried the below code to solve it. Actually, I am adding a visual webpart in a SharePoint page. Adding webpart is a post back event so !postback is always false each time I'm adding the webpart to page, and I'm getting an error at the else loop because the object reference is null.
我尝试了下面的代码来解决它。实际上,我在 SharePoint 页面中添加了一个可视化 webpart。添加 webpart 是一个回发事件,所以每次我将 webpart 添加到页面时 !postback 总是 false,并且我在 else 循环中收到错误,因为对象引用是null.
if (!IsPostBack){
ViewState["postids"] = System.Guid.NewGuid().ToString();
Cache["postid"] = ViewState["postids"].ToString();
}
else{
if (ViewState["postids"].ToString() != Cache["postid"].ToString()){
IsPageRefresh = true;
}
Cache["postid"] = System.Guid.NewGuid().ToString();
ViewState["postids"] = Cache["postid"].ToString();
}
How do I solve this problem?
我该如何解决这个问题?
回答by Vinoth
This article could be of help to you http://www.codeproject.com/Articles/68371/Detecting-Refresh-or-Postback-in-ASP-NET
这篇文章可能对你有帮助 http://www.codeproject.com/Articles/68371/Detecting-Refresh-or-Postback-in-ASP-NET
you are adding a Guid to your view state to uniquely identify each page. This mechanism works fine when you are in the Page class itself. If you need to identify requests before you reach the page handler, you need to use a different mechanism (since view state is not yet restored).
您正在向视图状态添加 Guid 以唯一标识每个页面。当您在 Page 类本身中时,此机制工作正常。如果需要在到达页面处理程序之前识别请求,则需要使用不同的机制(因为视图状态尚未恢复)。
The Page.LoadComplete event is a reasonable place to check if a Guid is associated with the page, and if not, create one.
Page.LoadComplete 事件是检查 Guid 是否与页面相关联的合理位置,如果没有,则创建一个。
check this http://shawpnendu.blogspot.in/2009/12/how-to-detect-page-refresh-using-aspnet.html
检查这个 http://shawpnendu.blogspot.in/2009/12/how-to-detect-page-refresh-using-aspnet.html
回答by lathomas64
using the viewstate worked a lot better for me as detailed here. Basically:
使用 viewstate 对我来说效果更好,详情见此处。基本上:
bool IsPageRefresh = false;
//this section of code checks if the page postback is due to genuine submit by user or by pressing "refresh"
if (!IsPostBack)
{
ViewState["ViewStateId"] = System.Guid.NewGuid().ToString();
Session["SessionId"] = ViewState["ViewStateId"].ToString();
}
else
{
if (ViewState["ViewStateId"].ToString() != Session["SessionId"].ToString())
{
IsPageRefresh = true;
}
Session["SessionId"] = System.Guid.NewGuid().ToString();
ViewState["ViewStateId"] = Session["SessionId"].ToString();
}
回答by dx_over_dt
If you want to detect a refresh on an HTTP GET rather than only POSTs, here's a hacky work-around that, in modern browsers, mostly works.
如果您想检测 HTTP GET 上的刷新,而不仅仅是 POST,这里有一个 hacky 解决方法,在现代浏览器中,它大多有效。
Javascript:
Javascript:
window.onload = function () {
// regex for finding "loaded" query string parameter
var qsRegex = /^(\?|.+&)loaded=\d/ig;
if (!qsRegex.test(location.search)) {
var loc = window.location.href + (window.location.search.length ? '&' : '?') + 'loaded=1';
window.history.replaceState(null, document.title, loc);
}
};
C#:
C#:
public bool IsPageRefresh
{
get
{
return !string.IsNullOrEmpty(Request.QueryString["loaded"]);
}
}
When the page loads, it will change add a QueryString parameter of loaded=1without reloading the page (again, this--window.history.replaceState--only works in post-archaic browsers). Then, when the user refreshes the page, the server can check for the presence of the loadedparameter of the query string.
当页面加载时,它会改变添加一个 QueryString 参数loaded=1而不重新加载页面(同样,这 -- --window.history.replaceState仅适用于后古浏览器)。然后,当用户刷新页面时,服务器可以检查loaded查询字符串的参数是否存在。
Caveat: mostlyworks
警告:大多数情况下有效
The case where this doesn't work is when the user clicks the Address Bar and presses enter. That is, the server will produce a false-positive, detecting a refresh, when odds are, the user actually meant to reload the page fresh.
这不起作用的情况是当用户单击地址栏并按下 时enter。也就是说,服务器会产生一个误报,检测到刷新,当可能性很大时,用户实际上打算重新加载页面。
Depending on your purposes, maybe this is desirable, but as a user, it would drive me crazy if I expected it to reset the page.
根据您的目的,这也许是可取的,但作为用户,如果我期望它重置页面,那会让我发疯。
I haven't put too much thought into it, but it mightbe possible to write some magic in order to distinguish a refresh from a reset via the address bar using any/all of:
我没有考虑太多,但可能会写一些魔术,以便使用以下任何/全部地址栏区分刷新和重置:
SessionState(assumingSessionStateis enabled) and the value of theloadedQueryString parameter- the
window.onbeforeunloadevent listener - keyboard events (detecting F5and Ctrl + Rto quickly change the URL back to removing the
loadedQueryString parameter--though this would have a false-negative for clicking the browser's refresh button) - cookies
SessionState(假设SessionState已启用)和loadedQueryString 参数的值- 该
window.onbeforeunload事件监听器 - 键盘事件(检测F5并Ctrl + R快速更改 URL 以删除
loadedQueryString 参数——尽管这会导致点击浏览器的刷新按钮的错误否定) - 饼干
If someone does come up with a solution, I'd love to hear it.
如果有人确实提出了解决方案,我很乐意听到。
回答by Narender Kumar
Another way to check page refresh. I have written custom code without java script or any client side.
另一种检查页面刷新的方法。我编写了没有 Java 脚本或任何客户端的自定义代码。
Not sure, it's the best way but I feel good work around.
不确定,这是最好的方法,但我感觉很好。
protected void Page_Load(object sender, EventArgs e)
{
if ((Boolean)Session["CheckRefresh"] is true)
{
Session["CheckRefresh"] = null;
Response.Write("Page was refreshed");
}
else
{ }
}
protected void Page_PreInit(object sender, EventArgs e)
{
Session["CheckRefresh"] = Session["CheckRefresh"] is null ? false : true;
}
回答by Roberto
Simple Solution
简单的解决方案
Thought I'd post this simple 3 line solution in case it helps someone. On post the session and viewstate IsPageRefresh values will be equal, but they become out of sync on a page refresh. And that triggers a redirect which resets the page. You'll need to modify the redirect slightly if you want to keep query string parameters.
以为我会发布这个简单的 3 行解决方案,以防它对某人有所帮助。在发布会话和视图状态 IsPageRefresh 值将相等,但它们在页面刷新时变得不同步。这会触发重置页面的重定向。如果要保留查询字符串参数,则需要稍微修改重定向。
protected void Page_Load(object sender, EventArgs e)
{
var id = "IsPageRefresh";
if (IsPostBack && (Guid)ViewState[id] != (Guid)Session[id]) Response.Redirect(HttpContext.Current.Request.Url.AbsolutePath);
Session[id] = ViewState[id] = Guid.NewGuid();
// do something
}

