介紹:
我正在評估一個 asp.net Web 項目應用。它有一些可擴展性問題。意味著當網(wǎng)站訪問量增加的時候。系統(tǒng)將會變得緩慢。當我查看應用日志。我找到了大量的ThreadAbortException. 這個應用大量的使用了Response.Redirect(是的 endResponse= true),這個就是可擴展性問題的根源。通過endResponse = false在Response.Redirect將會解決這個問題. 但這樣做會導致應用程序出現(xiàn)一些奇怪的問題。因為應用程序?qū)⒓僭O在Response.Redirect 將在當前頁面停止執(zhí)行.除此之外你需要處理一些安全隱患,因為你的應用程序是假設頁面事件永遠不會執(zhí)行重定向之后。在這篇文章中,我將講述一個簡單的方法來解決這些問題,并取得良好性能
說明:
比方說你有一個web表單,需要驗證一些條件并在條件不符時重定向用戶跳轉(zhuǎn)。
| 123456789101112 | PRotected void Page_Load(object sender, EventArgs e){var condition = ......;if (!condition){Response.Redirect("SomePage.aspx");}}protected void btnSave_Click(object sender, EventArgs e){// Save Data Here} |
這樣做很好,但這會影響可擴展性能。因為它將會終止線程池.現(xiàn)在,只需要用Response.Redirect("Unauthorized.aspx", false)替換Response.Redirect("Unauthorized.aspx"). 這將解決線程終止的問題,但不會停止當前頁面生命周期. 也就是說,你有需要確保 btnSave_Click事件(和所有其他頁面時間)因為只要允許btnSave_Click事件執(zhí)行任何人都可以很容易地發(fā)送POST請求. 為了解決這個問題我推薦使用RedirectUser擴展方法。
| 123456789101112131415161718192021222324252627282930313233 | 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.<span id="6_nwp" style="width: auto; height: auto; float: none;"><a id="6_nwl" href="http://cpro.baidu.com/cpro/ui/uijs.php?adclass=0&app_id=0&c=news&cf=1001&ch=0&di=128&fv=18&is_app=0&jk=281390770ff04e69&k=asp&k0=asp&kdi0=0&luki=4&n=10&p=baidu&q=06011078_cpr&rb=0&rs=1&seller_id=1&sid=694ef00f77901328&ssp2=1&stid=0&t=tpclicked3_hc&tu=u1922429&u=http%3A%2F%2Fwww%2Eadmin10000%2Ecom%2Fdocument%2F3189%2Ehtml&urlid=0" target="_blank" mpid="6" style="text-decoration: none;"><span style="color:#0000ff;font-size:14px;width:auto;height:auto;float:none;">asp</span></a></span>x");}}protected void btnSave_Click(object sender, EventArgs e){if (Response.IsRequestBeingRedirected){return;}// Save Data Here}} |
使用RedirectUser 第一個好處是它將首先使用對于應用程序具有良好擴展性的Response.Redirect(with endResponse= false) 方法。.第二個好處就是在你多次調(diào)用這個方法后它不會覆蓋先前的Response.Redirect(如果有的話). 第三個好處是它會調(diào)用HttpApplication.CompleteRequest用來處理 ASP.NET運行時所有通過的事件以及過濾HTTP管道信息(不是頁面生命周期管道信息).另外你需要注意在btnSave_Click事件中檢查Response.IsRequestBeingRedirected.我也希望你把所有的內(nèi)部控制放到 Response.IsRequestBeingRedirected檢查,
| 12345678 | <form id="form1" xml |