ASHX Handler TutorialUse the ASHX file format in the ASP.NET framework. Create a Handler.ashx file.
This page was last reviewed on Sep 28, 2022.
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.
Code 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.
Url example:
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.
Part of Web.config file, XML:
<system.web> <urlMappings enabled="true"> <add url="~/Default.aspx" mappedUrl="~/Handler.ashx"/> </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.
Test We can test the new configuration and ASHX file on the local machine. Now click the green arrow to run your website.
ASHX code-behind file, C#:
<%@ WebHandler Language="C#" Class="Handler" %> 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 = "image/png"; context.Response.WriteFile("~/Flower1.png"); } 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.
ASHX modified code-behind, C#:
<%@ WebHandler Language="C#" Class="Handler" %> using System; using System.Web; public class Handler : IHttpHandler { public void ProcessRequest (HttpContext context) { HttpResponse r = context.Response; r.ContentType = "image/png"; // // Write the requested image // string file = context.Request.QueryString["file"]; if (file == "logo") { r.WriteFile("Logo1.png"); } else { r.WriteFile("Flower1.png"); } } 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.
IsReusable 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 Sep 28, 2022 (rewrite).
© 2007-2022 sam allen.
see site info on the changelog.