Problem: You want to create an ASP. NET file, which is not an aspx file. It can dynamically return an image, XML file, or other non-HTML files.
Solution: Use the ashx file.
1. Use ASHX handlers
First, we should review the goal of using the ASHX file. What we need to do is to use the ASHX file in an address and dynamically return the content.
Querystring is used. The final address format is (example ):
Http://dotnetperls.com /? File = name
Start: you can add a new ashx file through these steps: Open your ASP. NET web site; Right-click the project and select "Add New Item... "; a" Add New Item "dialog box is displayed. Select" Generic Handler ". Now
A new ashx file is generated.
2. automatically generate code
We need to note the code automatically generated in the ashx file. It defines two parts of the IHttpHandler interface. ProcessRequest () determines whether the ashx file is requested or displayed. You cannot modify this inherited interface or delete
Except its method.
3. Handing handler
It is generally advisable to map an older URL or path to your new ashx file. To be backward compatible with and Optimize search engines, you can obtain the handler to take over an old URL. How to implement it? Use urlMappings;
<System. web>
<UrlMappings enabled = "true">
<Add url = "~ /Default. aspx "mappedUrl = "~ /Handler. ashx "/>
</UrlMappings>
URL mappings: the web. config configuration above will automatically connect one URL to another. Now, when Default. aspx is requested
, Your ashx file will take over. This means that you can map Default. aspx to your handler.
4. Add an image
Here we talk about what you can do with the ashx file. Find an image you like. Add it to your website project. For example, I chose an image named "flower1.png ". Next, we will use this image in the ashx file.
5. Modify the ashx File
There are two parts in your ashx file. Here, we must modify the ProcessRequest () method. We can change the ContentType and Response content of this file. Modify Your ashx file as follows.
~~~ ASHX code-behind file (C #)~~~
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;
}
}
}