Use httpHandle to handle image file requests
Step 1: Create a class that inherits from IHttpHandler. The Code is as follows:
C # code
Using System;
Using System. Web;
Namespace CustomHandler {
Public class JpgHandler: IHttpHandler {
Public void ProcessRequest (HttpContext context ){
// Obtain the physical path of the file server
String FileName = context. Server. MapPath (context. Request. FilePath );
// If UrlReferrer is empty, a default anti-leeching image is displayed.
If (context. Request. UrlReferrer. Host = null ){
Context. Response. ContentType = "image/JPEG ";
Context. Response. WriteFile ("/error.jpg ");
} Else {
// If UrlReferrer does not contain the host domain name of your website, a default anti-leeching image is displayed.
If (context. Request. UrlReferrer. Host. IndexOf ("yourdomain.com")> 0 ){
Context. Response. ContentType = "image/JPEG ";
Context. Response. WriteFile (FileName );
} Else {
Context. Response. ContentType = "image/JPEG ";
Context. Response. WriteFile ("/error.jpg ");
}
}
}
Public bool IsReusable {
Get {return true ;}
}
}
}
Step 2: Compile to DLL
Csc/t: library CustomHandler. cs
Step 3: add the compiled DLL reference to the bin folder of the current site
Step 4: register the Handler in Web. Config
C # code
<System. web>
<HttpHandlers>
<Add path = "*. jpg ,*. jpeg ,*. gif ,*. png ,*. bmp "verb =" * "type =" CustomHandler. jpgHandler, CustomHandler "/>
</HttpHandlers>
</System. web>
// Verb indicates the method used to request this file. It can be post or get, and * indicates all access methods. CustomHandler. JpgHandler indicates the namespace and class name, And CustomHandler indicates the Set Name.