How to Create an Asynchronous HTTP Handler in ASP.NET 4.5

Introduction

The ability to create HTTP handlers is not new to ASP.NET. However, ASP.NET 4.5 makes it easy for you to create asynchronous HTTP handlers with the new async/await keywords and Tasks. This article illustrates how an asynchronous HTTP handler can be created and consumed in an ASP.NET 4.5 web application.

Creating HTTP Handlers in ASP.NET

Traditionally HTTP handlers are classes that implement the IHttpHandler interface. You can also create an asynchronous HTTP handler by implementing the IHttpAsyncHandler interface. Asynchronous HTTP handlers are advantageous in situations where asynchronous processing can improve the overall performance of the application. The IHttpAsyncHandler interface requires you to write methods of the form BeginProcessRequest() and EndProcessRequest() methods. In ASP.NET 4.5 you can use the new async/await keywords and Tasks to achieve the same effect with simplified design.  Under ASP.NET 4.5 you can create a class that inherits from the HttpTaskAsyncHandler class and then override certain methods (as discussed later in this article).

NOTE:
Detailed discussion of async/await keywords and Tasks is beyond the scope of this article. You may read Working with Asynchronous Operations in ASP.NET 4.5 Web Forms for the basic understanding of these concepts.

Sample Asynchronous HTTP Handler

To understand how asynchronous HTTP handlers are created in ASP.NET 4.5, let's develop a simple example. Suppose that you have an ASP.NET web site with one or more web forms. On each of the web forms you wish to display advertisements. The advertisements are not statically placed on the web forms. They reside in a SQL Server database and at runtime you need to fetch them so as to render them onto the pages. Additionally, you also need to track the impressions each advertisement is receiving.

The following figure shows the Entity Framework for the sample database tables Ads and AdStats.

The Entity Framework

The Entity Framework

As you can see the Ads table has only two columns, viz. Id and Markup. The Markup column contains the HTML markup of the advertisement. The AdStats table stores information about ad impressions such as UserIP, UserAgent and TargetUrl.

To display an advertisement on web forms and to track the ad statistics you will create an asynchronous HTTP handler. In this specific scenario, creating an asynchronous HTTP handler rather than a synchronous one is beneficial because the ads are independent of the web form content and can be processed asynchronously. To create the asynchronous HTTP handler add a new Generic Handler (*.ashx) to the web application.

Add a new Generic Handler

Add a new Generic Handler

Change the default definition of the Generic Handler class as shown below:

<%@ WebHandler Language="C#" Class="MyHandler" %>

using System;
using System.Web;
using System.Threading.Tasks;
using System.Linq;

public class MyHandler : HttpTaskAsyncHandler
{
   ...
}

As shown above the MyHandler class inherits from the HttpTaskAsyncHandler base class. The HttpTaskAsyncHandler class is provided by ASP.NET 4.5 and you need to override its ProcessRequestAsync() method. The following code shows a sample implementation of the overridden method:

public override async Task ProcessRequestAsync(HttpContext context)
{
    string userIP = context.Request["REMOTE_ADDR"];
    string targetUrl = context.Request.QueryString["url"];
    string userAgent = context.Request.Browser.Browser;

    string adMarkup = await GetAdAsync();
    context.Response.Write("document.write('" + adMarkup + "');");
        
    string result = await SetStatsAsync(targetUrl, userIP, userAgent);
}

 As you can see the ProcessRequestAsync() method is an asynchronous method. Inside ProcessRequestAsync(), details about the web form requesting an advertisement are captured. These details include the user's IP address, the URL of the target web form and the requesting browser. The code then gets the details of advertisement from the database by calling the GetAdAsync() method. It also saves the ad statistics to the database by calling the SetStatsAsync() method.

The GetAdAsync() and SetStatsAsync() methods are quite similar in nature and are shown below.

private async Task<string> GetAdAsync()
{
    var func = Task<string>.Factory.StartNew(() => GetAdFromDb());
    await func;
    return func.Result;
}
private async Task<string> SetStatsAsync(string targeturl, string userip, string useragent)
{
    var func = Task<string>.Factory.StartNew(() => SaveStatsToDb(targeturl,userip,useragent)); 
    await func;
    return func.Result;
}

Both of these methods start a new Task and run the actual database access code on it using two helper methods: GetAdFromDb() and SaveStatsToDb(). These helper methods are shown below.

private string GetAdFromDb()
{
    System.Threading.Thread.Sleep(5000);
    DatabaseEntities db=new DatabaseEntities();
    var data = (from item in db.Ads
                select item).SingleOrDefault();
        
    return data.Markup;
}
private string SaveStatsToDb(string targeturl, string userip, string useragent)
{
    DatabaseEntities db = new DatabaseEntities();
    AdStat stat = new AdStat();
    stat.AdId = 1;
    stat.TargetUrl = targeturl;
    stat.UserIP = userip;
    stat.UserAgent = useragent;
    db.AdStats.Add(stat);
    db.SaveChanges();
        
    return "Data saved successfully!";
}

The GetAdFromDb() method simply retrieves the first record from the Ads table. In a real world situation you will have some ad selection logic here. It then returns the ad Markup to the caller. Notice that the GetAdFromDb() method introduces a delay of 5 seconds by calling the Sleep() method. This is done purely for the purpose of testing and you can remove this line once the application is complete. The SaveStatsToDb() method stores the target URL, user's IP and user agent (browser) to the AdStats table.

Using the Sample HTTP Handler in a Web Form

Now that your asynchronous HTTP handler is ready, let's see how it can be used in a web form. Add a web form to the web application and place a <script> tag in it as shown below.

<script type="text/javascript" src="http://localhost:49183/AsyncHTTPModuleHandler/MyHandler.ashx?url=<%= Request.Path%>">
</script>

As you can see the <script> tag points to the MyHandler.ashx, the asynchronous HTTP handler you developed in the previous section. It also passes the Request.Path of the current web form in a querystring parameter. This way you are making a call to the asynchronous HTTP handler where the <script> tag is placed.

Before running the web form, add some advertisement data in the Ads table and then run the web form. The following figure shows a sample run of the web form.

Sample run of a web form

Sample run of a web form

As you can see from the above figure the text "Hello World!" is part of the web form whereas the text "This is an advertisement!" is the part of an advertisement and is stored in the database. Also notice that when you run this web form "Hello World!" is displayed immediately and the advertisement is displayed after 5 seconds due to the delay introduced in the code. After running the web form check the database to verify the ad statistics are stored as expected.

Summary

ASP.NET 4.5 allows you to create asynchronous HTTP handlers easily. An asynchronous HTTP handler is a class that inherits from the HttpTaskAsyncHandler base class. This article illustrated how an asynchronous HTTP handler can be created and consumed in a web forms application.



Related Articles

Downloads

Comments

  • Fake Oakley Miss Conduct wholesale shop

    Posted by civtqqmpw on 07/06/2013 12:50pm

    Replica Oakley Sunglasses ,From 1975 to 1980, the Oakley team has been protective glasses produced wild racing into your mainstream. In your everyday living, a couple sunglasses, for your T-shirt and jeans, optical single product range, children's play stars a powerful sense of nostalgia sweeping the style industry. These colors are a stylish choice strikingly help the Oakley sunglasses and transformed into the framework with the real provocation, there should be irrespective your design framework lovers sunglasses. Fake Oakley Holbrook ,Oakleys is undoubtedly among his or her class, has become the boom of an trend, they've already found many of the popular Hollywood performers. High quality and unique Oakley sunglasses as much as completely UV filter lens. It's possible to look forward to Oakley sunglasses, popular soon. The sunglasses initially utilized to reduce eye fatigue and light stimulate the harm as a shade of. From the direct sun is not going to get rid of the threat, however expressed in epidermis and eyes can tolerate the expression in the extended spread of ultraviolet radiation damage. The attention can not view the using Oakley sunglasses to be able to slow up the photovoltaic ultraviolet radiation. Fake Oakleys ,Oakley is popular around the globe range of products for example shoes, watches, backpacks and sweatshirts, however are very famous to its attractive color, people cheap Oakley sunglasses are very well known. The way lovers also has an access to the garments customized in line with the selection of the precise features to ensure these are the best match the kind of clothing. Fake Ray Ban ,Oakley may be valued at the investment of said and done, the people's lifestyle, sports or polarized sunglasses will get the correct product manufacturers from this. Oakley have been the earth's top athletes trial engaged in numerous projects, to check all possible imaginable case. Sac Longchamp Pliage Fleuri ,Oakley sunglasses can also be very practical, Oakley, the sunglasses will help you get rid of sun burn, and give you 100% UV blockage. Different requirements can be purchased as clothing accessories, in order to meet the demands of females, too much clothing and components in acquiescence to the current style. Are turning to the most important items on your sunglasses, polarized contacts are available through the sunglasses warehouse supplies, if you live an excellent fashionable pursuit.

    Reply
  • beats hovedtelefoner by dr. dre ved, du kan nemt se folk

    Posted by wanzixiao on 06/04/2013 06:22am

    [url=http://www.beatsbydrdredanmark.blinkweb.com/]beats by dre danmark[/url] Beats By Dr. Dre Beats Wireless har annonceret et trådløst Bluetooth-headset. Dette er udformningen af den populære Solo HD og kan let kobles med en smartphone eller tablet. Den nye model er også udstyret med ControlTalk, med en mikrofon i øret og alle nødvendige kontroller. Beats By Dr. Dre introducerer Beats trådløse Bluetooth hovedtelefoner Beats By Dr. Dre Beats introducerer den trådløse Bluetooth-hovedtelefoner lytteren fuld musikalsk frihed. [url=http://www.nyebeatsbydrdre.350.com/]beats by dre danmark[/url] Så hvorfor kan meget vel blive set alle omkring dig Beats hovedtelefoner? Dette er helt sikkert helt en god måde Dre headset sammen med lyd annullerer headsets BIDRAGET er bare ikke headsets hypotese. Enhver sang på dette tidspunkt har jeg vokset til at være en god must, mange inden for den nødvendige. tage et godt udseende med alle gode? Song overlegen tone overstrømmende på dine vegne, i din lethed, ingen tvivl om du kender overlegen sang indgivet til din mobiltelefon eller blot film battler. [url=http://www.beatsbydrdredanmark.blinkweb.com/]beats by dre danmark[/url] Beats “Supreme Sound” Headsets forskydninger, der er valgt i form af vej erklæring – selv om det faktum, at faktisk syntes at tale om! “Jeg er en god overdreven person i hans teenageår” The hovedtelefon anker var oprindeligt strålende sammen med betydelig med hensyn til neon . Men i tidligere tider flere aldre, har kunderne allerede blevet anvendt som vil high-end konkurrerende virksomheder anvender personlig bank kan synes, sammen med Beats indgået et system var oprindeligt det meste af tydeligt. Artiklen udformet en slags in-house industri team – tidligere var næsten hele pakken jobbet oprindeligt dyrket ud – at drage fordel af luftstrøm sammen med forbedre enhver mp3. Den populære sti i disse dage har en god imprintede Great Tone.

    Reply
  • Nice one there

    Posted by Slalaleasyday on 03/15/2013 05:26pm

    Nice Post. ---------- I love http://youtube.com

    Reply
  • Html format

    Posted by parwej on 02/09/2013 10:01am

    Thanks for your article. I was looking same thing but I am facing issue with html string. When I tried to return the html string then getting javascript error on the page and not able to render the same string. Do you have any idea? http://stackoverflow.com/questions/14426501/httptaskasynchandler-and-html-string

    Reply
  • why do we need await at multiple places

    Posted by RK on 12/20/2012 08:20am

    Nice article, question on using Await at several places, seems to be redundant.

    Reply
  • Nice article

    Posted by RK on 12/20/2012 08:19am

    Nice article to demo the Async Http handler with simple instruct ions. Kudos to Bipin. One question thought, I felt that "await" in this context (string adMarkup = await GetAdAsync();) is redundant as there is async operation ( await func;) done inside the GetAdAsyn() method.

    Reply
  • webtekspace.blogspot.in

    Posted by webtekspace.blogspot.in on 12/02/2012 07:56am

    webtekspace.blogspot.in

    Reply
  • Question on the script tag

    Posted by Alex on 11/28/2012 08:56am

    Thanks for the informative article. I don't quite follow the part about setting the src attribute of a script tag to the url of the Handler. It doesn't appear to render anything in the web form when I run the sample code from your download. I have tried constructing my own version as well with the same results. Am I missing something obvious?

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: October 29, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Are you interested in building a cognitive application using the power of IBM Watson? Need a platform that provides speed and ease for rapidly deploying this application? Join Chris Madison, Watson Solution Architect, as he walks through the process of building a Watson powered application on IBM Bluemix. Chris will talk about the new Watson Services just released on IBM bluemix, but more importantly he will do a step by step cognitive …

  • Packaged application development teams frequently operate with limited testing environments due to time and labor constraints. By virtualizing the entire application stack, packaged application development teams can deliver business results faster, at higher quality, and with lower risk.

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds