JumpStart # 13–Async HttpHanlders in ASP.Net 4.5

Before looking at the code, Read about – What is JumpStart?

 

Async Handler -

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

using System;
using System.Web;
using System.Threading.Tasks;
using System.Net;

//Implement HttpTaskAsyncHandler for async operations
public class CustomAsyncHandler : HttpTaskAsyncHandler
{
    // Specify that this process is going to be a async process
    public override async Task ProcessRequestAsync(HttpContext context)
    {
        // Get the Image FileName which needs to be downloaded from QueryString
        string _imageName = context.Request.QueryString["ImageName"];
        
        //Contruct Image download URL - PLEASE CHANGE THIS TO YOUR CORRESPONDING URL
        // For Demo purpose I ave used Localhost Url, but in reality it can be internal source
        Uri _u = new Uri(String.Format("http://localhost:2214/Images/{0}", _imageName), UriKind.RelativeOrAbsolute);

        // Create WebClient instance to make image download
        WebClient webClient = new WebClient();
        
        // Use await to methion that this point might be long running operation
        byte[] _image = await webClient.DownloadDataTaskAsync(_u);
        
        // Write the content to response stream
        context.Response.BinaryWrite((byte[])_image);
    }
}

 

Async Handler Consumption in ASPX Page -

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">
    protected void Page_Load(object sender, EventArgs e)
    {
        // Create a List and bind it to Repeater
        List<string> imageSource = new List<string>();
        imageSource.Add("Image1.jpg");
        imageSource.Add("Image2.jpg");
        imageSource.Add("Image3.jpg");

        Repeater1.DataSource = imageSource;
        Repeater1.DataBind();
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Repeater ID="Repeater1" runat="server">
            <ItemTemplate>
                <img src='<%# string.Format("CustomAsyncHandler.ashx?ImageName={0}",Container.DataItem) %>' height="100px" width="100px"></img>
            </ItemTemplate>
        </asp:Repeater>
    </div>
    </form>
</body>
</html>

 

Solution Structure -

AsyncHttpHandler1

 

Output on WebPage -

AsyncHttpHandler2

You may also like...