Response.End()是否被認為是有害的?這篇KB文章說ASP.NET的Response.End()中止線程。反光鏡顯示它看起來是這樣的:public void End(){
if (this._context.IsInCancellablePeriod)
{
InternalSecurityPermissions.ControlThread.Assert();
Thread.CurrentThread.Abort(new HttpApplication.CancelModuleException(false));
}
else if (!this._flushing)
{
this.Flush();
this._ended = true;
if (this._context.ApplicationInstance != null)
{
this._context.ApplicationInstance.CompleteRequest();
}
}}這對我來說很殘酷。如KB文章所述,應用程序中的任何代碼如下Response.End()不會被執(zhí)行,這違反了最不驚訝的原則。就像Application.Exit()在WinForms應用程序中。引發(fā)的線程中止異常。Response.End()是不可捕捉的,因此將代碼包圍在try...finally不會滿足的。這讓我想知道我是否應該總是避免Response.End().有人能建議我什么時候使用Response.End(),何時Response.Close()什么時候HttpContext.Current.ApplicationInstance.CompleteRequest()?參考文獻:里克·斯特拉的博客.根據(jù)我收到的信息,我的回答是,是,Response.End是有害的,但在某些有限的情況下是有用的。使用Response.End()作為不可捕獲的拋出,立即終止HttpResponse在特殊情況下。在調(diào)試過程中也會很有用。避Response.End()完成例行反應.使用Response.Close()立即關閉與客戶端的連接。每這篇MSDN博客文章,這種方法不適用于正常的HTTP請求處理。您不太可能有充分的理由調(diào)用此方法。使用CompleteRequest()結(jié)束正常的請求。CompleteRequest使ASP.NET管道跳轉(zhuǎn)到EndRequest事件之后的HttpApplication事件完成。所以如果你打電話CompleteRequest,然后向響應寫入更多內(nèi)容,寫將被發(fā)送到客戶端。
3 回答

拉丁的傳說
TA貢獻1789條經(jīng)驗 獲得超8個贊
ThreadAbortException
Response.End()
Response.End()

Smart貓小萌
TA貢獻1911條經(jīng)驗 獲得超7個贊
// Add headers for a csv file or whateverResponse.ContentType = "text/csv"Response.AddHeader("Content-Disposition", "attachment; filename=report.csv")Response.AddHeader("Pragma", "no-cache")Response.AddHeader("Cache-Control", "no-cache") // Write the data as binary from a unicode stringDim buffer As Byte()buffer = System.Text.Encoding.Unicode.GetBytes(csv)Response .BinaryWrite(buffer)// Sends the response bufferResponse.Flush()// Prevents any other content from being sent to the browser Response.SuppressContent = True// Directs the thread to finish, bypassing additional processingHttpContext.Current.ApplicationInstan ce.CompleteRequest()
- 3 回答
- 0 關注
- 916 瀏覽
添加回答
舉報
0/150
提交
取消