Creating an Http Handler in ASP

. Sunday, January 8, 2012
  • Agregar a Technorati
  • Agregar a Del.icio.us
  • Agregar a DiggIt!
  • Agregar a Yahoo!
  • Agregar a Google
  • Agregar a Meneame
  • Agregar a Furl
  • Agregar a Reddit
  • Agregar a Magnolia
  • Agregar a Blinklist
  • Agregar a Blogmarks

It’s possible to create a type that implements the IHttpHandlerinterface and have it respond
to any pattern of URL. The advantage is you have full control over the URL, and the URL of the
request doesn’t need to correspond to a physical file. The downside is that IIS configuration is
required to map the URL into the framework, and ASP.NET configuration is required to map
the URL to your specific handler.
The alternative is to use the built-in, simple handler factory. This handler is mapped to
files with an ASHX extension. The WebHandlerdirective is used to point an ASHX page at a type
that implements the IHttpHandlerinterface. Visual Studio adds a file with this directive to
your project via the Generic Handler option in the Add New Item dialog window.

<%@ WebHandler Language="C#" Class="MyHandler" %>
using System;
using System.Web;
using System.Web.Caching;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
public class MyHandler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
byte[] b;
object id = context.Request.QueryString["BookId"];
b = (byte[])context.Cache[string.Format("Book{0}",id)];
if (b == null)
{
SqlConnection cn = new SqlConnection(ConfigurationManager.
ConnectionStrings["Library_local"].ConnectionString);
string sql = "select CoverImage from BookCoverImage";
sql += " where bookid = @BookID";
SqlCommand cm = new SqlCommand(sql, cn);
cm.Parameters.Add("@BookId", SqlDbType.Int).Value = id;
cn.Open();
SqlDataReader dr = cm.ExecuteReader();
if (!dr.Read())
context.Response.End();
b = (byte[])dr[0];
context.Cache.Insert(string.Format("Book{0}", id),
b,
null,
DateTime.Now.AddSeconds(60),
Cache.NoSlidingExpiration);
dr.Close();
cn.Close();
}
context.Response.OutputStream.Write(b, 0, b.Length - 1);
}
public bool IsReusable {
get { return true; }
}
}

0 comments: