ASHX Handler Tutorial
This page was last reviewed on Nov 29, 2023.
Dot Net Perls
ASHX handler. Some ASP.NET files are dynamic. They are generated with C# code or disk resources. These files do not require web forms. Instead, an ASHX generic handler is ideal.
Getting started. Go to the Website menu and select "Add New Item". Select the "Generic Handler" item, and you will get a new file with some code in it called Handler.ashx.
Handle query strings. We use the ASHX file in a URL, and have it dynamically return content. The ASHX file handler will return data based on the query string.
Detail The important part is ProcessRequest(), which will be invoked whenever the Handler.ashx file is requested.
Tip You should not change the interface inheritance or remove either of the members.
Mappings. It is often desirable to map an older URL or path to your new ASHX file. For backwards compatibility, you will want the new handler to take over an old URL in your site.
Tip To do this, use urlMappings. Alternatively you can use more complex RewritePath methods.
Info The Web.config markup will link one URL to another. When the Default.aspx page is requested, your Handler.ashx file will take over.
<system.web> <urlMappings enabled=&quot;true&quot;> <add url=&quot;~/Default.aspx&quot; mappedUrl=&quot;~/Handler.ashx&quot;/> </urlMappings> ...
Code example. Your handler has two parts. Here we modify the ProcessRequest method. We can change the ContentType of the file and the Response content.
So Modify your Handler.ashx to be similar to the following, with your image ContentType and file name.
Detail We can test the new configuration and ASHX file on the local machine. Now click the green arrow to run your website.
<%@ WebHandler Language=&quot;C#&quot; Class=&quot;Handler&quot; %> using System; using System.Web; public class Handler : IHttpHandler { public void ProcessRequest (HttpContext context) { // Comment out these lines first: // context.Response.ContentType = "text/plain"; // context.Response.Write("Hello World"); context.Response.ContentType = &quot;image/png&quot;; context.Response.WriteFile(&quot;~/Flower1.png&quot;); } public bool IsReusable { get { return false; } } }
Add functionality. The example here so far is relatively useless. All it does is allow us to pipe an image through an ASHX handler.
Info You can add any functionality (logging code or referrer logic) to the handler in the C# language.
Also Developers commonly need to use the QueryString collection on the Request.
So You can use the Request.QueryString in the Handler just like you would on any ASPX web form page. The code is the same.
<%@ WebHandler Language=&quot;C#&quot; Class=&quot;Handler&quot; %> using System; using System.Web; public class Handler : IHttpHandler { public void ProcessRequest (HttpContext context) { HttpResponse r = context.Response; r.ContentType = &quot;image/png&quot;; // // Write the requested image // string file = context.Request.QueryString[&quot;file&quot;]; if (file == &quot;logo&quot;) { r.WriteFile(&quot;Logo1.png&quot;); } else { r.WriteFile(&quot;Flower1.png&quot;); } } public bool IsReusable { get { return false; } } }
What this does. The above code receives requests and then returns a different file based on the QueryString collection value. It will return one of 2 images from the 2 query strings.
URL: http://www.dotnetperls.com/?file=logo File query string: logo File written: Logo1.png
URL: http://www.dotnetperls.com/?file=flower File query string: flower File written: Flower1.png
Uses. The code here could be used as a hit tracker that counts visitors and logs referrers. This could provide a more accurate visit count than server logs.
Handlers versus web pages. ASP.NET web forms have many events and a detailed initialization and event model. You don't need that for dynamic images, XML, or binary files.
Image Output
Performance. Is there any performance advantage or change to using ASHX files? These files are less complex. They are more streamlined and involve less code.
And As you can imagine, firing more than 10 events each time a request is handled is a fair amount more expensive than only firing one event.
Detail This can improve performance and decrease memory pressure by not repeatedly destroying the handler.
Summary. We used ASHX custom handlers in an ASP.NET website. We combined urlMappings with query strings on custom handlers to greatly simplify and streamline back-end web site code.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 29, 2023 (simplify).
© 2007-2024 Sam Allen.