Is Response.End() considered harmful?

2018-12-31 04:22发布

This KB Article says that ASP.NET's Response.End() aborts a thread.

Reflector shows that it looks like this:

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();
        }
    }
}

This seems pretty harsh to me. As the KB article says, any code in the app following Response.End() will not be executed, and that violates the principle of least astonishment. It's almost like Application.Exit() in a WinForms app. The thread abort exception caused by Response.End() is not catchable, so surrounding the code in a try...finally won't satisfy.

It makes me wonder if I should always avoid Response.End().

Can anyone suggest, when should I use Response.End(), when Response.Close() and when HttpContext.Current.ApplicationInstance.CompleteRequest()?

ref: Rick Strahl's blog entry.


Based on the input I've received, my answer is, Yes, Response.End is harmful, but it is useful in some limited cases.

  • use Response.End() as an uncatchable throw, to immediately terminate the HttpResponse in exceptional conditions. Can be useful during debugging also. Avoid Response.End() to complete routine responses.
  • use Response.Close() to immediately close the connection with the client. Per this MSDN blog post, this method is not intended for normal HTTP request processing. It’s highly unlikely that you would have a good reason to call this method.
  • use CompleteRequest() to end a normal request. CompleteRequest causes the ASP.NET pipeline to jump ahead to the EndRequest event, after the current HttpApplication event completes. So if you call CompleteRequest, then write something more to the response, the write will be sent to the client.

Edit - 13 April 2011

Further clarity is available here:
- Useful post on MSDN Blog
- Useful analysis by Jon Reid

标签: .net asp.net
8条回答
伤终究还是伤i
2楼-- · 2018-12-31 05:06

I've never considered using Response.End() to control program flow.

However Response.End() can be useful for example when serving files to a user.

You have written the file to the response and you don't want anything else being added to the response as it may corrupt your file.

查看更多
骚的不知所云
3楼-- · 2018-12-31 05:07

I've only used Response.End() as a testing/debugging mechanism

<snip>
Response.Write("myVariable: " + myVariable.ToString());
Response.End();
<snip>

Judging from what you have posted in terms of research, I would say it would be a bad design if it required Response.End

查看更多
登录 后发表回答