Search code examples
iishttpmodule

How can I cleanly terminate HTTP Transaction in OnBeginRequest?


I'm writing a modest transaction processor with an HTTP interface. The client posts the transaction details in the body of the POST.

All I really need is the OnBeginRequest handler. By the time I get to the bottom of this event, I'm done. No need to continue with the IIS pipeline processing on the server.

So I put a Response.End there at the bottom. This 'works' however it does throw an exception which I simply catch and suppress.

  1. Should I be concerned about this from either a performance or quality standpoint?

  2. Is there any way to accomplish this more cleanly?

    private void OnBeginRequest(object sender, EventArgs e)
    {
        HttpContext ctx = HttpContext.Current;
    
        try
        {
            if (ctx.Request.RequestType == "POST" && ctx.Request.IsSecureConnection)
            {
                // Here's where processing is implemented...
    
               ctx.Response.StatusCode = 200;
               ctx.Response.Write("OK");
            }
            else
            {
               ctx.Response.StatusCode = 403;
               ctx.Response.Write("BAD");
            }
        }
        catch (Exception ex)
        {
            ctx.Response.StatusCode = 500;
            ctx.Response.Write("ERROR");
        }
    
        try
        {
            ctx.Response.End();
        }
        catch { }
    }
    

Solution

  • in my opinion, this is the only way to terminate request using Response.End. another thing you could try is HttpContext.Current.ApplicationInstance.CompleteRequest(); This will end all further processing of the request. Your handler is not the only handler in the pipeline, so this will cancel further processing of other handlers after yours and send the response immediately to the client.

    HttpApplication.CompleteRequest Method