what is Generic Handler and how to Maintain session data in Generic Handler .ashx page

In asp.net there are several new feautres exists .Net Framework 3.5 and later One of the most important feature is Generic handler page.what is Generic handler page in asp.net?what is the purpose of using Generic handle page in .Net and how to maintain a session in Generic handler page?These are the things that i want to discuss in this Article with code snippets and real time images

In Asp.net the Generic handler page act as a Server (in Client-server Technology terms).In which a Client will send a request to the server and server process the request and in turn sends to the client.Here the aspx page act as a client and Generic handler act as a server process the request and send back to client.

To open a New Generic Handler page in your Asp.net :

First we need add a New website after adding a website right click on the website Add a New Item there you can select Generic Handler page.

The page will have an extension of .Ashx.

Unlike the Ordinary page the i.e.aspx page the ashx page class inherits the interface IHttphandler where as the aspx page inherits the System.web.UI.Page

see the below Real image how .ashx.cs page looks like

Now we will look an example how .aspx and .ashx pages will request and response the request in Coding.

To call the Handler i.e ashx page from the aspx page we need to write the below Code snippet.

imgThumb.ImageUrl="~/Controls/ShowImage.ashx?Id=" + id;

In this Example I have a Datalist i want to bind images to the Datalist.Here i am sending image ids to the ashx page.

I do n't want to hit the database every time.I had already a result set/Dataset(image information) in my aspx page.Now i need to use/transfer the resultset/Dataset in my ashx page and filter the dataset with the help of query string to get the image path from the dataset and than convert into Binary format in the ashx page. But Unfortunately the .ashx page does n't contain Default session class or default import of System.web.Sessionstate so we need to import this name space and with this we need to inherits the IReadOnlySessionState in the ashx page.

How to get session data in my ashx page

see the below image how it look likes....

and now i will get Session data in my ashx page with the below code..

dataset ds = (Dataset)context.Session["sesdst"];

Now i will filter the dataset with the query string and convert in Byte array...

After using the above code i will bind my images to the Datalist for corresponding image ids..

Uses of Ashx page :

1)Dynamic image Generation.

2)Returning Rest-based xml or Json data.

3)Custom Html.

Attachments

Article by sriramaA Good advice from parent to a Child , Master to a Student , Scholar to an Ignorant is like a doctor prescribed pill it is bitter to take but when they take it will do all good for them --- Bhushan