Some ASP. net files are dynamic. They is generated with C # code or disk resources. These files do not require Web forms. Instead, an ASHX generic handler is ideal. It can return an image from a query string, the write XML, or any other data.
Tutorial
First, we review the goal of using ASHX files in the ASP. NET Web Development framework. We Use the ASHX file with a URL, and have it dynamically return content. We'll use the query string. The final URLs would look like this.
URL Examplehttp://www.dotnetperls.com/?file=name
Getting started. We list the steps to add a new ASHX file. To does this, open your ASP. NET Web site. Go to the Website menu and click on the first menu item there, "Add New Item ...". This would present the ADD New Item dialog box.
Then : Select the "Generic Handler" item, and you'll get a new file with some code in it called Handler.ashx.
Autogenerated code
What purpose does the autogenerated code in the the ASHX file has? It defines the parts of the IHttpHandler interface. The important part is ProcessRequest (), which would be invoked whenever the Handler.ashx file is requested.
Tip: You should the interface inheritance or remove either of the members.
Mappings
It is often desirable to map a older URL or path to your new ASHX file. For backwards compatibility and for search engine optimization, you'll probably want the new handler to take over a old URL in your site.
Tip: To does this, use urlmappings. Alternatively you can use more complex rewritepath methods.
Part of Web. config file:xml<system.web> <urlmappings enabled= "true" ><add url= "~/ Default.aspx "mappedurl=" ~/handler.ashx "/> </urlMappings> ...
URL mappings. The above Web. config markup would automatically link one URL to another. When the Default.aspx page is requested, your handler.ashx file would take over. This means your can map the default page in a directory to your handler.
Urlmappings for redirects
ADD Example Image
We mention what are you can does with the ASHX file involving images. Find your favorite image on your disk or on the Internet and add it to your website project. For my example, the image I chose is "Flower1.png".
Next: We'll use this image in the Handler.ashx file. We implement an image-based handler.
Modify Handler.ashx
Your handler has a parts. Here we modify the ProcessRequest method. We can change the ContentType of the file and the Response content. Modify your handler.ashx to is similar to the following, with your image ContentType and file name.
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;}} }
Test Handler
Here we test the new configuration and ASHX file to the local machine. Now click the green arrow to run your website on the development server. You should see the image in your browser. This is the result of the handler.
ADD functionality
The example is relatively useless. All it does are allow us to pipe a image through an ASHX handler. 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. You can use the request.querystring in the Handler just as 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 = Co ntext. 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's this does. The above code receives requests and then returns a different file based on the QueryString collection value. It would return one of the images from the strings. The strings it returns is shown.
URL 1 Url:http://www.dotnetperls.com/?file=logofile query String:logo file written:Logo1.png URL2 : Http://www.dotnetperls.com/?file=flowerFile query string:flower file written:Flower1.png
Test query string
Does all the work? Yes, but it's always important to test. Open your browser. And on the path, add query strings like those shown above. What happens was that ASP. Internally maps the Default.aspx page to your handler.ashx.
Then : The Handler.ashx file receives the query string and writes the appropriate file.
Uses
The code here could is used as a hits tracker that counts visitors and logs referrers. This could provide a more accurate visit count than server logs, because of browser and bot differences.
handlers versus Web pages. ASP. NET Web Forms inherit from the Page class. This provides them with many events and a detailed initialization and event model. You don ' t need this for dynamic images, XML, or binary files.
Image Output
Performance
Is there any performance advantage or change to using ASHX files? These files is less complex and they does not involve as many events. They is more streamlined and involve less code, and the is a advantage.
as can imagine, firing more than ten events each time a request was handled is a fair amount more expensive th An only firing one event. Therefore, there would be some performance advantage to using ASHX files where possible.
isreusable: I don't know precisely what's the IsReusable property does. Much of the supporting code is not in the ASHX file itself.
But : My reading indicates it can improve performance and decrease memory pressure by not repeatedly destroying the handler.
Choose handlers
Here I want to propose some guidelines on to choose custom handlers and when to prefer ASPX Web Form pages. Handlers is better for binary data, and Web Forms is best for rapid development.
Use Web Forms ... If you have the simple HTML pagesasp.net custom controlssimple dynamic pages with usehandlers ... If you have binary filesdynamic image viewsperformance-critical Web pagesxml filesminimal Web pages
Control Trees
In the ASP. Web Forms use a concept called control trees where the parts of Web pages is stored in an OBJEC T model. Use custom handlers if you don't require the custom control tree or the whole HTML Web Form framework.
Note: This would result in greater performance. And the code would be much simpler code to debug.
Summary
We used ASHX custom handlers in an ASP. Website. This could fill many different important web site functions. We combine urlmappings with query strings on the custom handlers to greatly simplify and streamline Back-end Web site code.
"Reprint" Http://www.dotnetperls.com/ashx
ASP. ASHX Handler