首先看看IhttpHandler接口都有哪些成员
![](https://images.cnblogs.com/cnblogs_com/freegarden/2009-09-20_145138.png)
1:添加ISAPI扩展名映射(完成iis对jpg等图片的注册,如果只是通过vs2008浏览网站,就不需要注册)
2:实现继承IhttpHandler接口的类 比如JpgHandler.cs
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.IO;
using System.Globalization;
namespace CustomHandler
{
public class JpgHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
//获取当前Request对象
HttpRequest req = context.Request;
//从Request对象中获取所请求文件的物理路径
string IMG_Path = req.PhysicalPath;
string ContentType;
//判断请求的URL是否为本站内的URL
if (req.UrlReferrer != null && req.UrlReferrer.Host.Length > 0)
{
if (CultureInfo.InvariantCulture.CompareInfo.Compare(req.Url.Host, req.UrlReferrer.Host, CompareOptions.IgnoreCase) != 0)
{
IMG_Path = context.Server.MapPath("~/images/error.jpg");
}
}
//根据路径名获取输出内容类型
ContentType = GetContentType(IMG_Path);
//判断文件是否存在
if (File.Exists(IMG_Path))
{
context.Response.StatusCode = 200;
context.Response.ContentType = ContentType;
context.Response.WriteFile(IMG_Path);
}
else
{
context.Response.StatusCode = 404;
context.Response.Status = "无法找到您请求的文件";
}
}
public bool IsReusable
{
get { return true; }
}
/// <summary>
/// 此方法用于从路径获取输出的MIME类型
/// </summary>
/// <param name="path">文件路径</param>
/// <returns>对应的MIME类型</returns>
private string GetContentType(string path)
{
//获取文件的扩展名
string extension = Path.GetExtension(path);
string contentType;
//判断扩展名对应的Mime类型
switch (extension)
{
case ".gif":
contentType = "image/gif";
break;
case "image/jpeg":
contentType = "image/jpeg";
break;
case ".png":
contentType = "image/png";
break;
default:
contentType = "";
break;
}
//返回mime类型
return contentType;
}
}
}
3:在web.config
<httpHandlers>
<add verb="*" path="*.jpg" type="CustomHandler.JpgHandler,CustomHandler"/>
</httpHandlers>
Type 逗号前是类的名称,逗号后类生成后的程序集名称(如果是code内的类就不需要写程序集)
测试方法:通过vs浏览网站下的图片可以正常显示,copy img的url。发布个网站下 img将出现图片无法访问
![](https://images.cnblogs.com/cnblogs_com/freegarden/2009-11-17_144620.gif)
![](https://images.cnblogs.com/cnblogs_com/freegarden/2009-11-17_144642.gif)