Is using Config.Current.Pipeline.Rewrite the most efficient way to implement watermarking on hotlinked files?

StackOverflow https://stackoverflow.com/questions/17003002

سؤال

I'm running ImageResizer on iis7 in Integrated mode. I just want to make sure I'm not introducing unnecessary overhead with this code in my Application_Start. The intent here is to watermark certain images (folder based, then size based) when the request does not come from within my domain (e.g. hotlinked files or Googlebot or Pinterest, etc.):

  Config.Current.Pipeline.Rewrite += delegate(IHttpModule mysender, HttpContext context, IUrlEventArgs ev)
  {
     if (context.Request.UrlReferrer.Host != "www.mydomain.com")
     {
        //Check folder
        string folder1 = VirtualPathUtility.ToAbsolute("~/images/products");
        string folder2 = VirtualPathUtility.ToAbsolute("~/images/product-showcase");
        string folder3 = VirtualPathUtility.ToAbsolute("~/images/frills");
        if (ev.VirtualPath.StartsWith(folder1, StringComparison.OrdinalIgnoreCase) || ev.VirtualPath.StartsWith(folder2, StringComparison.OrdinalIgnoreCase) || ev.VirtualPath.StartsWith(folder3, StringComparison.OrdinalIgnoreCase))
        {
           //Estimate final image size, based on the original image being 300x300. 
           System.Drawing.Size estimatedSize = ImageBuilder.Current.GetFinalSize(new System.Drawing.Size(300, 300),
                           new ResizeSettings(ev.QueryString));
           if (estimatedSize.Width > 100 || estimatedSize.Height > 100)
           {
              //It's over 100px, apply watermark
              ev.QueryString["watermark"] = "watermarkname";
           }
        }
     }
  };

edit/solution: for working code, 3rd line should be:

     if (context.Request.UrlReferrer == null || (context.Request.UrlReferrer != null && context.Request.UrlReferrer.Host != "www.mydomain.com"))

This will watermark the images that are 1) directly accessed OR 2) referenced in a page on an outside site. Amen.

Thanks, John

هل كانت مفيدة؟

المحلول

In general, this is the correct and most performant way to do this.

You do need to verify context.Request.UrlReferrer is not null before accessing the Host property.

While watermarking is a 'non-violent' method that can work in a whitelist approach like this, in general a blacklist-based approach to target particular offenders is less problematic.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top