Have you ever noticed that there are many more requests for image resources in your server request log? This may be because someone has leeched your image on their website, which will occupy the bandwidth of your server. The following method tells you how to implement a custom routehandler in ASP. net mvc to prevent others from leeching your images.
First, let's review the situation when a request is sent to the Asp.net MVC site. IIS receives the request and forwards the request to Asp.net. Then, based on the URL, or more specifically: the extension of the requested file. in iis7 integrated mode (default mode), all requests will match Asp.net. In IIS6, you can use wildcards to achieve the same effect as iis7.
In ASP. NET MVCProgramThe first part involved in is the urlroutingmodule, which isSystem. Web. RoutingThe urlroutingmodule is used to check whether the requested URL matches the file in the local disk for the first time. If the request matches, urlroutingmodule sends the request directly back to IIS, and IIS sends the request according to the address. If the urlroutingmodule does not find a matching file on the disk. It checks the routecollection structure to determine whether to continue to pass the request. urlroutingmodule introduces routehandler and the matched path entry (mvcroutehandler by default ). Then, appropriate httphandler will be introduced to process and request-related logic. By default, the httphandler will be mvchandler. however, image files are generally stored in a subdirectory in the program. The core routemodule does not have this capability because the system directly requests the image URL and sends it back to IIS preferentially, the routehandler cannot be executed at this time.
Normally, you can retrieve static files on the disk through Asp.net. However, if you want to execute some business logic instead of directly making such files respond to requests. You need to implement it programmatically at some key points. You can setRoutetable. routes. routeexistingfiles = trueTo avoid default actions on existing files. Phil haack (Asp. net MVC Senior Program Manager) is called "Nuclear Weapons-level options", whether it is CSS, JS, Doc, PDF and other files, In this mode, all files need to be processed by routing. So the key to this is that the request for static files cannot match the file on the disk. This will force routemodule to search for the route table (of course, The routehandler process will be introduced. This is easy to do. You only need to point the element to a fictitious directory. For example, your images are stored in the images folder under the root directory of the website, and the element pointing to a "graphics" folder will not match the existing files.
To do this, you need to do the following:
- Register a route for an image request
- Create routehandler to process such requests
- Create httphandler to process actual requests
First, we start with step 2, because it will not be compiled successfully if routehandler is not created but registered in the routing table.
Routehandler is very simple, it is the implementation of iroutehandler, it has only one method --Ihttphandler iroutehandler. gethttphandler (requestcontext ):
Public ClassImageroutehandler: iroutehandler {PublicIhttphandler gethttphandler (requestcontext ){Return NewImagehandler (requestcontext );}}
For the actual httphandler:
Public Class Imagehandler: ihttphandler { Public Imagehandler (requestcontext context) {processrequest (context );} Private Static Void Processrequest (requestcontext) {var response = requestcontext. httpcontext. response; var request = requestcontext. httpcontext. request; var Server = requestcontext. httpcontext. server; var validrequestfile = requestcontext. routedata. values [" Filename "]. Tostring (); Const String Invalidrequestfile =" Thief.gif "; Var Path = server. mappath (" ~ /Graphics/ "); Response. Clear (); response. contenttype = getcontenttype (request. url. tostring ()); If (Request. servervariables [" Http_referer "]! =Null & Request. servervariables [" Http_referer "]. Contains (" Mikesdotnetting.com ") {Response. transmitfile (path + validrequestfile );} Else {Response. transmitfile (path + invalidrequestfile);} response. End ();} Private Static String Getcontenttype ( String URL ){ Switch (Path. getextension (URL )){ Case ". Gif ": Return " Image/GIF "; Case " . Jpg ": Return " Image/JPEG "; Case " . PNG ": Return " Image/PNG "; Default : Break ;} Return Null ;} Public Void Processrequest (httpcontext context ){} Public Bool Isreusable { Get { Return False ;}}}
AboveCodeIn ihttphandlerProcessrequest,There are two reloads. The first one isPublic void processrequest (httpcontext context ),Here, we ignore this overload. In the MVC program, we pass in the requestcontext object as the parameter, rather than the httpcontext object. The processrequest method is called in the imagehandler constructor. In the above Code, processrequest first checks whether the request image address is input into my domain (that is, the webpage that references the image is my website rather than other people's). If not, it returns another image. The returned images depend on you. I have seen many such images, some of which contain non-harmonious content. you can even return a 1 px transparent GIF, or make the 404 Not found ....
Of course, you can also take other steps at this point. For example, you certainly want Google to index your images, so if the referenced Link contains "images. google "you can return real images. You can also use logs to record images that fail to be leeched on other websites.
The last step is to register a routetable for the image request, which is used to indicate imageroutehandler to process this part of the request. In the global. axax file, add:
Routes. Add ("Imagesroute",NewRoute ("Images/{filename}",NewImageroutehandler ()));
Hope this articleArticleIt not only helps you Stop leeching vampires, but also gives you a deeper understanding of the bottom layer of Asp.net MVC so that you can expand it when you have other requirements in the future.
-----------------------------------------------------------------------------
Link: http://www.mikesdotnetting.com/Article/126/ASP.NET-MVC-Prevent-Image-Leeching-with-a-Custom-RouteHandler