我一直在使用以下大部分的Global.asax(Application_Start)代码,效果很好(related)。当外部启动请求时,我以这种方式配置它以在某些目录上提供水印图像(热链接/直接请求)。
//ImageResizer
Config.Current.Pipeline.Rewrite += delegate(IHttpModule mysender, HttpContext context, IUrlEventArgs ev)
{
if (context.Request.UrlReferrer == null || (context.Request.UrlReferrer != null && context.Request.UrlReferrer.Host != "www.mydomain.com"))
{
//File has been requested from outside of the target domain, so see if it meets criteria for watermarking
string folder1 = VirtualPathUtility.ToAbsolute("~/images/products");
string folder2 = VirtualPathUtility.ToAbsolute("~/images/product-showcase");
if (ev.VirtualPath.StartsWith(folder1, StringComparison.OrdinalIgnoreCase) || ev.VirtualPath.StartsWith(folder2, StringComparison.OrdinalIgnoreCase))
{
//Image is within the targeted folders. If the requested file is jpg, change extension to png
if (Path.GetExtension(ev.VirtualPath) == ".jpg") ev.VirtualPath = Path.ChangeExtension(ev.VirtualPath, ".png");
//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 and change the ouput format
ev.QueryString["watermark"] = "style";
ev.QueryString["bgcolor"] = "ffffff";
ev.QueryString["format"] = "jpg";
}
}
}
};
但是,我刚刚修改了我的网页,以便通过添加& format = jpg查询字符串来提供我的产品图像。我知道一个正确的MIME类型提供给Web浏览器,这真的很酷,但是文件名呢? 例如/images/products/widget1.png?watermark=c&format=jpg仍然指的是png图像,即使服务格式是jpg。我担心的是,谷歌图像等刮刀或图像聚合器可能1)想要将URL剥离到文件名或2)考虑MIME类型并通过更改扩展名重新引用它。我不确定谷歌图片实际上对上面的网址做了什么,并且想要处理这两种情况。 [也许如果我知道,我可以更好地针对这种情况]
为了处理场景2,我刚刚添加了上面的路径扩展检查,一切都得到了顺利处理。顺便说一下,目标目录中只有.png图像。
对于场景1,对.png文件的外部请求会通过,但该文件实际上被编码为.jpg,这就是打击的部分。我希望我可以重写扩展名。我尝试使用Response.Redirect,但由于我在Application_Start中工作,我无法访问它。
答案 0 :(得分:1)
在使代码复杂化之前,请确保您知道要修复的内容。据我所知,你描述的问题是理论上的,而且不存在。如果您能解释您已经看到的并且正在尝试解决的实际问题,那将会有所帮助。
重写不会改变浏览器看到的内容 - 它发生在服务器中。只有HTTP重定向才会更改浏览器或Google可见的URL,这是非常不可取的,因为它会使延迟加倍。
使用Content-disposition HTTP header可以影响下载或保存图像时使用的文件名,但这不会影响浏览器URL或SEO。