2

I need to test a condition in several ASPX code-behind files and, in some cases, would like to completely bypass the normal page load process so that the corresponding ASPX page is not loaded. Intead, I'd like to send a custom response to the browser that's written from a code-behind method.

Does anyone know where to start- what method(s) in the page lifecycle to override and the best technique to ensure that my custom Response.Write is sent to the browser while the normal ASPX page content is suppressed?

Thanks.

3 Answers3

7

Probably the easiest way to do it - use Page_Load().

protected void Page_Load(object sender, EventArgs e)
{
    bool customResponse = true;
    if (customResponse)
    {
        Response.Write("I am sending a custom response");
        Response.End(); //this is what keeps it from continuing on...
    }
}
Seibar
  • 68,705
  • 38
  • 88
  • 99
6

The "easy" way to do it, with Response.End() is terrible for performance, throwing an exception which terminates the thread.
http://blogs.msdn.com/b/tmarq/archive/2009/06/25/correct-use-of-system-web-httpresponse-redirect.aspx
http://weblogs.asp.net/hajan/archive/2010/09/26/why-not-to-use-httpresponse-close-and-httpresponse-end.aspx

I had the same question and solved it this way. It's a two-step process: First call HttpApplication.CompleteRequest() and exit your processing. Next override Render() so that the base method is not called. The example code then becomes:

bool customResponse = true;

protected void Page_Load(object sender, EventArgs e)
{
    if (customResponse)
    {
        Response.Write("I am sending a custom response");
        this.Context.ApplicationInstance.CompleteRequest();
        return;   // Bypass normal processing.
    }
    // Normal processing...
}

protected override void Render(HtmlTextWriter writer)
{
    if (!customResponse)
        base.Render(writer);        // Then write the page as usual.
}
Keith Robertson
  • 791
  • 7
  • 13
0

It really depends what you're responding to, is it a posted Form field, authentication info etc...? The method shown using Page_Load will work, but anything before that point in the page lifecycle will also execute.