ASP.NET 4.5 provides us with the full C# language features described previously in Chapter 2, Exploring the Top New Features of the CLR. Also, the additional methods and features make it easier for us to work with asynchronous language features.
This helps enormously in writing asynchronous HTTP modules and handlers.
Performance is also improved, as the model is asynchronous; it doesn't keep the thread blocked until the request is completed.
We are going to create an asynchronous HTTP module. An HTTP module allows us to intercept HTTP requests for modifying those requests so we can generate a response in a customized way.
AsyncHTTPModule
.System.Web
assembly.CustomModule
. Note that we could as well add an item of type ASP.NET
, which would do most of the following for us:Using
clause to the System.Web
pageIHttpModule
private async Task getWebPageContent(object caller, EventArgs e) { WebClient wc = new WebClient(); var result = await wc.DownloadStringTaskAsync("http://www.packtpub.com/"); HttpApplication app = (HttpApplication)caller; app.Response.Write(result); }
Using
clause to System.Net
to use the WebClient
method.Init
method:public void Init(HttpApplication context) { // We use the EventHandlerTaskAsyncHelper to wrap the task based method to use with the "old" async programming model. EventHandlerTaskAsyncHelper asyncHelper = new EventHandlerTaskAsyncHelper(getWebPageContent); // The helper class instance generates the Begin/End methods for us from a Task Function. context.AddOnPostAuthorizeRequestAsync(asyncHelper.BeginEventHandler, asyncHelper.EndEventHandler); }
dispose
method. Leaving it empty will do for now.In this scenario, the request thread is released when the request has been initiated and a new thread is created when the request finishes, with the response being received on a brand new thread.
Implementing an asynchronous HTTP module fits in perfectly with the core of this behavior.
We implemented IHttpModule
and created an asynchronous task. This method can be awaited, which means that it will not block the thread on which it is executed; when it has finished, it will continue from the point where it was awaited, control being returned to the caller of the async method. When an async method or the task it returns finishes, it invokes its continuation from where it left off.
After defining the asynchronous method, which will download the www.packtpub.com website asynchronously and return it as the response, we need to assign it so it can be used by the HTTP module.
We do this with the EventHandlerTaskAsyncHelper
class, which we get from the System.Web
namespace.
This helper method is meant to integrate a task-based method with the programming model exposed by the ASP.NET HTTP pipeline, which will assign the Begin
and End
methods to the async helper's BeginEventHandler
and EndEventHandler
event handlers.