Wednesday, 14 November 2012

Asynchronous HttpHandlers in ASP.NET 4.5

HttpHandlers are responsible to handle all types of HTTP requests that an ASP.NET web server receives. Page is also an HttpHandler, as it is derived from IHttpHandler interface.

Need of creating an HttpHandler may arise when we want to have more control over the way a request is handled. There can be scenarios where we have to generate some content dynamically like a captcha image to show on a page or generate some file that the user will download. In such cases, HttpHandler is the choice we stop at.

The HttpHandler may perform operations like fetching data from a remote location (like service calls, heavy DB queries) and some I/O operations on the disc. As sever would take considerable amount of time to complete such requests, it is better to perform them asynchronously.

To create an asynchronous HttpHandler in older versions of ASP.NET, the handler class has to be derived from IHttpAsyncHandler and implement its members. In ASP.NET 4.5, this process is simplified with the abstract class HttpTaskAsyncHandler. It has an abstract method ProcessRequestAsync, returning a Task. We can use the magical async and await keywords inside this method.

Following is a sample implementation an HttpHandler derived from HttpTaskAsyncHandler:

public class AsyncHandler : HttpTaskAsyncHandler
{
    public override async Task ProcessRequestAsync(HttpContext context)
    {
        //Calling a service to fetch data
        var client = new DataServiceClient();
        var getCitiesTask = client.GetCitiesAsync();

        //Setting folder path and file name
        string folderPath = context.Server.MapPath("Downloadables");
        string fileName = "cities.xlsx";

        //Asynchronously calling a method to store data obtained from service in an excel file
        await Task.Factory.StartNew(() => FillDataIntoExcel(getCitiesTask.Result, folderPath, fileName));

        //Sending the excel file to user's system
        context.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        context.Response.WriteFile(folderPath + "\\" + fileName);
    }
}

You can download the complete source code of the handler here: Download Source. The sample application also contains implementation of an asynchronous web form.

Happy coding!

2 comments: