Goto: "translated" ASP. NET MVC uses custom Routehandler to prevent picture hotlinking

Source: Internet
Author: User
Tags goto httpcontext servervariables

Have you ever noticed a lot more requests for picture resources in your server request log? This may be caused by someone hotlinking your image on their website, which will take up your server bandwidth. Here's a way to show you how to implement a custom Routehandler in ASP. NET MVC to prevent others from hotlinking your pictures.

First, let's review the scenario when a request is sent to an ASP. Net. NET MVC site, and IIS receives the request and transfers the request to ASP, then depending on the URL, or more specifically: the extension of the requested file. In IIS7 Integrated mode (default mode), All requests will be matched to ASP. In IIS6, you can use wildcards to achieve the same effect as IIS7.

The first part involved in the ASP is UrlRoutingModule, which is part of the System.Web.Routing . UrlRoutingModule is used to check the URL of the request for the first time and whether the files on the local disk match. If it matches, UrlRoutingModule will send the request directly to Iis,iis according to the address. If UrlRoutingModule does not find a matching file on the disk. It examines the routecollection structure to determine whether the request continues to be delivered. UrlRoutingModule introduces Routehandler and matching path portals (Mvcroutehandler by default). The appropriate HttpHandler are then introduced to process and request the relevant logic. By default, This httphandler is going to be mvchandler. For picture files, which typically exist in a subdirectory of the program, the core Routemodule does not have the ability to send the URL of the image directly back to IIS, and the process cannot execute until Routehandler is introduced. .

Normally, it is possible to remove the static files on the disk by ASP. However, if you want to execute some business logic instead of just letting this type of file respond to the request. You need to implement it programmatically at some point in the way. You can avoid the default corresponding behavior for existing files by setting RouteTable.Routes.RouteExistingFiles = True . Phil Haack (Senior Program Manager for ASP. NET MVC) calls it "a nuclear-weapon-level option," in which all files need to be handled using routing, regardless of css,js,doc,pdf. So the key to ensuring this is that requests for static files cannot match the corresponding files on the disk. This forces Routemodule to find the route table (which, of course, introduces Routehandler). This is easy to do, just let the element point to a fictitious directory. For example, your image is stored under the Images folder in the root directory of the Web site, and the element points to a "graphics" folder that will not match the existing file.

To do this, you need to do the following:

    1. Registering a route for a request for a picture
    2. Create Routehandler to handle this kind of request
    3. Create HttpHandler to handle the actual request

We start with step 2 first, because if you do not create routehandler and you want to register in the routing table, this will not compile successfully.

Routehandler is very simple, it is the implementation of Iroutehandler, it has only one method-IHttpHandler Iroutehandler.gethttphandler (requestcontext RequestContext):

public class imageroutehandler:iroutehandler{Public  IHttpHandler Gethttphandler (RequestContext requestcontext)  {    return new ImageHandler (RequestContext);  }}

For the actual HttpHandler:

public class imagehandler:ihttphandler{Public ImageHandler (RequestContext context) {ProcessRequest (context); } private static void ProcessRequest (RequestContext requestcontext) {var response = RequestContext.HttpContext.Respo    Nse    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;} }}

In the above code, ProcessRequest in IHttpHandler, there are two overloads, the first is the public void ProcessRequest (HttpContext context) , Here we ignore this overload, in the MVC program, we pass in the RequestContext object as the argument, not the HttpContext object. The ProcessRequest method is called in the constructor of the ImageHandler, and in the code above, ProcessRequest first checks to see if the address of the requested picture is entered into my domain (that is, the page that references the picture is my site and not others). If not, a different picture is returned. Return what kind of picture depends on yourself, I have seen many kinds of such pictures, some contain discordant content. You can even return a 1px transparent GIF, or you can make 404 Not found ....

Of course, there are other steps you can take at this point, for example, you would want Google to index your images, so if the referenced link contains "Images.google" You can return to the real picture. You can also log on to other websites hotlinking your pictures are unsuccessful.

The final step is to register the request for the picture to RouteTable, to represent Imageroutehandler to process this part of the request, and in the Global.axax file, add:

Routes. ADD ("Imagesroute",                 new Route ("Images/{filename}", New Imageroutehandler ()));

Hopefully this article will not only help you stop those hotlinking vampires, but will also allow you to have a deeper understanding of the bottom of ASP, so you can expand it if you have other needs later.

-----------------------------------------------------------------------------

Original link: Http://www.mikesdotnetting.com/Article/126/ASP.NET-MVC-Prevent-Image-Leeching-with-a-Custom-RouteHandler

Http://www.cnblogs.com/CareySon/archive/2009/12/30/1636438.html

translated by: Careyson

Add: My is MVC5,IIS7, also need to add Web. config

<modules runallmanagedmodulesforallrequests= "true" > Only line.

Goto: "translated" ASP. NET MVC uses custom Routehandler to prevent picture hotlinking

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.