Wednesday 25 February 2009

HTTP Handlers and HTTP Modules

Every web request to an asp.net application is handledby http handlers.httphandlers are classes that are designated to process webrequest. There are separate handlers for each URL request.It means .aspx, .asmx file extensions are handled by different httphandlers.For example to request an asp.net page which has .aspx extension, request is handled by pagehandler,System.Web.UI.PageHandlerFactory class. Httphandler is class that implement IHTTPhandler interface.IHttphandler has a method void ProcessRequest(HttpContext context); and property bool IsReusable {get{;}set{;}}; It means customized httphandlers can be created.Reason to create customized httphandlers is that sometimes we need to process some functionality when a URL is requested ,however we don't want to place our code in aspx page as we don't need to process a page processing it would create overburden in processing. Let's look
at e-commerce asp.net application where top page displays product images. There must be hundereds of products and ofcourse each product has an image.in asp.netapplication image is not simply displayed through Picture Box control as in desktop application.Images are rather rendered through reponse object.we cannt simply use response object in same page or control(custom control) ..We need to separate image processing code from the current page. where to pass image id through url.therefore all image displaying code is placed in ProcessRequest method which Httpcontext as a parameter which current context. All httphandlers are also configured in web.config file, for example httphandler for .asmx
webservices ,Crystalreport are defined in web.config file as



<httpHandlers> remove verb="*" path="*.asmx"/> < add verb="*" path="*.asmx" validate="false"
type="System.Web.Script.Services.ScriptHandlerFactory,
System.Web.Extensions, Version=1.0.61025.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35"/>
< add verb="GET,HEAD" path="ScriptResource.axd"
type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions,
Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
validate="false"/>
"GET" path="CrystalImageHandler.aspx"
type="CrystalDecisions.Web.CrystalImageHandler, CrystalDecisions.Web,
Version=10.2.3600.0, Culture=neutral,
PublicKeyToken=692fbea5521e1304
"/> </httpHandlers>




Custom httphandlers should aslo be defined web.config file.This is called registering httphandlers , however there is also another method to register a httphandlers without web.config file changes.

Registering Httphandlers without web.config/Machine.config file changes.
using .ashx extension, httphandlers are registered automatically and all web requested that are processed through .ashx, are convereted to custom httphandlers.



  • Open any asp.net
    application.

  • Right click on soultion andclick on Add New Item.
  • From template select Generic
    handler.
  • Name it as
    ImageHandler.




here is class which is created inherited
from Ihttphandler and implement two memebers. The Class is created directly
under Web handler directive.


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

using
System;

using
System.Web;

public class ImageHandler :IHttpHandler
{

public void ProcessRequest (HttpContext context)
{

context.Response.ContentType = "text/plain";

context.Response.Write("Hello
World"
);

}

public bool IsReusable
{

get
{

return false;

}


}





ArrayList Databaseparams = new ArrayList();


Now we we will place our custom code to render an image in
processRquest Method.


if
(context.Request.Params.Count > 0)


{


try


{


System.IO.MemoryStream
m =
new
System.IO.
MemoryStream();


string id =
(context.Request.QueryString[0].ToString());


//a webservice where all data access code
is placed.


MultiPurposeWBS.MSheetService Ms = new
MultiPurposeWBS.
MSheetService();


DataSet ds =
Ms.Select(
"select * from DProducts where
ProductID="
+ int.Parse(id) + "", Databaseparams.ToArray());


foreach (DataRow r in ds.Tables[0].Rows)


{


context.Response.ContentType = "image/JPEG";


byte[] ar =
(
byte[])(r["Photo"]);


System.IO.MemoryStream
me =
new
System.IO.
MemoryStream();


me.Write((byte[])(r["Photo"]), 0,
ar.Length);



System.Drawing.Image
img = System.Drawing.
Image.FromStream(me);


System.Drawing.Size siz
=
new
System.Drawing.
Size(125,
160);


img = new
System.Drawing.
Bitmap(img,
siz);


img.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);


}


}


catch (Exception ex)


{


string str =
ex.Message;


System.Diagnostics.Debug.WriteLine(str);


}


finally


{


}


}



call this handler from another aspx page.

in the example i ve created a datalist. tag is defined in datalist with url:




<img
id="one" src ="Imagehandler.ashx?EmpID=<%#DataBinder.Eval(Container.DataItem, "ProductID")%>" />

product is passed with productid.so when datalist is populating data, each time img tag pass url with data and fetch reponse cache data , that is inserted in ashx , file..


Ihttphandler is helpful when rendering RSS feeds as xml with no html data.



No comments:

Post a Comment