簡體   English   中英

Page_Init上的警報消息

[英]Alert message on Page_Init

我有一個由PageBase類(所有頁面都將繼承該類)調用的安全類,如果嘗試,它將把用戶重定向到主頁或登錄頁面(取決於他們是否登錄)並訪問他們無權查看的頁面。 我想提醒用戶,例如

"You are not authorized to view this page, redirecting you"

或類似的東西。 我知道您可以從代碼背后調用javascript以向用戶顯示警報。

在我的PageBase類中(同樣,所有頁面都將從其繼承),有一個通用的Page_Init(..)方法,當我嘗試從那里調用我的js警報時,什么也沒有發生。 我在代碼中添加了斷點,並且代碼被命中,但是用戶沒有收到警報。 我認為這是因為Page_Init在頁面生命周期中為時過早,無法執行js,而這就是導致此問題的原因。

有沒有一種解決方法,而不必向每個單獨的頁面添加功能? 另外,這是我嘗試過的兩種方法:

System.Web.UI.Page page = HttpContext.Current.CurrentHandler as System.Web.UI.Page;
System.Web.UI.ScriptManager.RegisterStartupScript(page, page.GetType(), "alert", "alert('You do not have access to this page. You are being redirected')", true);

Response.Write("<script type='text/javascript'>alert('You do not have access to this page. You are being redirected');</script>");

問題不在於Page_Init上沒有任何頁面。 問題在於服務器沒有向瀏覽器發送任何內容,因為它在Page Lifecycle中還為時過早。 (更多來臨)

在正常情況下,即使您調用Response.Write,響應數據也不會發送到瀏覽器,直到Rendering事件為止。 通常可以通過在Response.Write BUT之后立即調用Response.Flush()來強制執行此操作,這通常會帶來意想不到的后果。 在Page_Init周期中,我認為調用Response.Flush()可能會引起很多問題。

只需使用“我們正在重定向”消息創建一個靜態html頁面,然后使用javascrip.SetTimeout方法倒計時並在幾秒鍾后使用javascript重定向,可能會更好。 這就是多年來在網絡上完成的方式。 如果未授權用戶,則您的基類可以簡單地重定向到此頁面。

“重定向”頁面的代碼。

<html>
 <head>
 <script type="text/javascript">
 function delayedRedirect(){
     window.location = "/default.aspx"
 }
 </script>
 </head>
 <body onLoad="setTimeout('delayedRedirect()', 3000)">
 <h2>You are not authorized to view this page, redirecting you</h2>
 </body>
 </html> 

您需要在基本頁面上的Page_Load事件中實現邏輯,如下所示:

ScriptManager.RegisterStartupScript(this, this.GetType(), "keykey", "alert('You do not have access to this page. You are being redirected'); window.location='http://caracol.com.co';", true);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM