HttpApplication.CompleteRequest()的作用是什么?

3

我用设计视图制作了一个简单的Web表单,并在代码后台上放置了两个方法:Page_LoadPage_PreRender,如下所示:

public partial class SamplePage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.ClearContent();
        Response.ClearHeaders();
        Response.StatusCode = (int)HttpStatusCode.NotFound;
        Respons.Write("Not Found");
        Context.ApplicationInstance.CompleteRequest();
    }

    protected void Page_PreRender(object sender, EventArgs e) // Why does this event get called? Should not the CompleteReqeust()
    {                                                         // cause the page to jump directly to the end of events pipeline?
        throw new NotImplementedException();
    }
}

此外,我已经阅读了许多关于Response.End()被称为“丑陋”、“危险”等的问答,甚至是在MSDN网站上。但是这让我感到困惑,如果如此的话,为什么Response.Redirect(string)仍然在内部使用Response.End()呢?
1个回答

1
在页面中覆盖 IHttpHandlerProcessRequest(HttpContext) 方法就足以实现这个技巧。
public partial class SamplePage : System.Web.UI.Page
{
    public override void ProcessRequest(System.Web.HttpContext context)
    {
        if (conditionTrue)
        {
            context.Response.StatusCode = 404;
            context.ApplicationInstance.CompleteRequest();
        }
        else
        {
            base.ProcessRequest(context);
        }
    }

    protected void Page_Load(object sender, EventArgs e) // This is not called also :P
    {
    }

    protected void Page_PreRender(object sender, EventArgs e) // Not called now :)
    {
        throw new NotImplementedException();
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接