介紹:
我正在評估一個 asp.net Web 項目應用。它有一些可擴展性問題。意味著當網站訪問量增加的時候。系統將會變得緩慢。當我查看應用日志。我找到了大量的 ThreadAbortException. 這個應用大量的使用了 Response.Redirect (是的 endResponse= true),這個就是可擴展性問題的根源。通過endResponse = false 在Response.Redirect將會解決這個問題. 但這樣做會導致應用程序出現一些奇怪的問題。因為應用程序將假設在 Response.Redirect 將在當前頁面停止執行.除此之外你需要處理一些安全隱患,因為你的應用程序是假設頁面事件永遠不會執行重定向之后。在這篇文章中,我將講述一個簡單的方法來解決這些問題,并取得良好性能
說明:
比方說你有一個web表單,需要驗證一些條件并在條件不符時重定向用戶跳轉。
1 2 3 4 5 6 7 8 9 10 11 12 | { var condition = ......; if (!condition) { Response.Redirect( "SomePage.aspx" ); } } protected void btnSave_Click( object sender, EventArgs e) { // Save Data Here } |
這樣做很好,但這會影響可擴展性能。因為它將會終止線程池.現在,只需要用Response.Redirect("Unauthorized.aspx", false)替換Response.Redirect("Unauthorized.aspx") . 這將解決線程終止的問題,但不會停止當前頁面生命周期. 也就是說,你有需要確保 btnSave_Click 事件(和所有其他頁面時間)因為只要允許btnSave_Click事件執行任何人都可以很容易地發送POST請求. 為了解決這個問題我推薦使用RedirectUser擴展方法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | public static class HttpResponseExtensions { public static void RedirectUser( this HttpResponse response, string url) { if (response.IsRequestBeingRedirected) return ; response.Redirect(url, false ); var context = HttpContext.Current; if (context != null ) { context.applicationInstance.CompleteRequest(); } } } public partial class WebForm : System.Web.UI.Page { protected void Page_Load( object sender, EventArgs e) { var condition = .....; if (!condition) { Response.RedirectUser( "Unauthorized.aspx" ); } } protected void btnSave_Click( object sender, EventArgs e) { if (Response.IsRequestBeingRedirected) { return ; } // Save Data Here } } |
使用 RedirectUser 第一個好處是它將首先使用對于應用程序具有良好擴展性的Response.Redirect(with endResponse= false) 方法。.第二個好處就是在你多次調用這個方法后它不會覆蓋先前的Response.Redirect(如果有的話). 第三個好處是它會調用 HttpApplication.CompleteRequest用來處理 ASP.NET運行時所有通過的事件以及過濾 HTTP 管道信息(不是頁面生命周期管道信息).另外你需要注意在 btnSave_Click事件中檢查 Response.IsRequestBeingRedirected.我也希望你把所有的內部控制放到 Response.IsRequestBeingRedirected 檢查,
1 2 3 4 5 6 7 8 | < form id = "form1" runat = "server" > <% if(!Response.IsRequestBeingRedirected){ %> < asp:Button ID = "btnSave" runat = "server" Text = "Save" OnClick = "btnSave_Click" /> <%--All the Other Controls--%> <%--All the Other Controls--%> <%--All the Other Controls--%> <%} %> </ form > |
另一件你需要注意的事情,當你使用一個復雜的控制(類似GridView, RadGrid, etc)這些擁有 選擇,插入,更新和刪除事件時。 當 Response.IsRequestBeingRedirected 為true時,你必須取消操作(插入,更新或刪除) 這些事件,下面是一個例子
1 2 3 4 5 6 7 8 | protected void GridView1_RowEditing( object sender, GridViewEditEventArgs e) { if (Response.IsRequestBeingRedirected) { e.Cancel = true ; return ; } } |
總結:
在這篇文章里,我向您展示如何使用Response.Redirect . 我同樣也發現了一些風險問題。可以采用Response.Redirect優化和技術以降低風險 .也同樣希望你喜歡這篇文章。
原文地址:using-response-redirect-effectively.aspx
新聞熱點
疑難解答