Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the point of HttpApplication.CompleteRequest()?

Tags:

asp.net

I have made a simple web form with some static HTML on the design view, and on the code behind I put on two methods: Page_Load and Page_PreRender as follows:

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

Moreover, I have read so many Q&As about Response.End() being "ugly", "dangerous", etc, even from MSDN website. But it puzzles me a lot, why if so the Response.Redirect(string) still uses Response.End() internally?

like image 426
Ghasan غسان Avatar asked Jan 28 '26 02:01

Ghasan غسان


1 Answers

Overriding IHttpHandler's ProcessRequest(HttpContext) in the Page is enough to do the trick.

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();
    }
}
like image 85
Ghasan غسان Avatar answered Jan 29 '26 19:01

Ghasan غسان



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!