|
使用httpHandle来实现,对图片文件的请求做专门的处理
第一步:创建一个类,继承自IHttpHandler,代码如下- using System.Web;
- namespace CustomHandler{
- public class JpgHandler : IHttpHandler{
- public void ProcessRequest(HttpContext context){
- // 获取文件服务器端物理路径
- string FileName = context.Server.MapPath(context.Request.FilePath);
- // 如果UrlReferrer为空,则显示一张默认的禁止盗链的图片
- if (context.Request.UrlReferrer.Host == null){
- context.Response.ContentType = "image/JPEG";
- context.Response.WriteFile("/error.jpg");
- }else{
- // 如果 UrlReferrer中不包含自己站点主机域名,则显示一张默认的禁止盗链的图片
- //string serverHost = context.Request.Url.Host;
- //Uri u = context.Request.UrlReferrer;
- //if (u == null || u.Host.ToLower() != serverHost.ToLower())
- 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; }
- }
- }
- }
复制代码 第二步:编译成DLL
第三步:添加编译好的DLL引用到当前站点的bin文件夹下
第四步:在Web.Config 中注册这个Handler- <system.web>
- <httpHandlers>
- <add path="*.jpg,*.jpeg,*.gif,*.png,*.bmp" verb="*" type="CustomHandler.JpgHandler,CustomHandler" />
- </httpHandlers>
- </system.web>
复制代码 //verb指的是请求此文件的方式,可以是post或get,用*代表所有访问方式。CustomHandler.JpgHandler表示命名空间和类名,CustomHandler表示程序集名。
如果发布网站的话,你会发现你的URL重写有可能会失效,如果失效的话就需要您设置一下IIS:
打开IIS,主目录-〉配置-〉映射-〉点击“插入”通配符应用程序映射-〉选择“C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll”,然后把勾选去掉(一定要去掉),然后确定。
上面设置完毕之后,就可以正常浏览了。
|
|