using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; namespace imgfilterdemo.App_Code { public class imgHandler : IHttpHandler { public bool IsReusable { get { return true; } } public void ProcessRequest(HttpContext context) { var path = context.Request.PhysicalPath; var patha = context.Request.PhysicalApplicationPath; if (!File.Exists(path)) { //不存在 则返回默认的图片 context.Response.WriteFile(patha+ "404.png"); } else { //图片存在 不做任何处理 context.Response.WriteFile(path); } context.Response.ContentType = "image/"+ context.Request.CurrentExecutionFilePathExtension.Replace(".",""); context.Response.End(); } } }
1、App_Code目录下新建上述类imgHandler.cs
2、对应的配置文件
集成模式
<system.webServer> <handlers> <add verb="*" name="imgHandler" type="imgfilterdemo.App_Code.imgHandler" path="*.png"/> <add verb="*" name="imgHandler1" type="imgfilterdemo.App_Code.imgHandler" path="*.gif"/> <add verb="*" name="imgHandler2" type="imgfilterdemo.App_Code.imgHandler" path="*.jpg"/> <add verb="*" name="imgHandler3" type="imgfilterdemo.App_Code.imgHandler" path="*.jpeg"/> </handlers> </system.webServer>
经典模式
<system.web> <httpHandlers> <add verb="*" type="imgfilterdemo.App_Code.imgHandler" path="*.png"/> <add verb="*" type="imgfilterdemo.App_Code.imgHandler" path="*.gif"/> <add verb="*" type="imgfilterdemo.App_Code.imgHandler" path="*.jpg"/> <add verb="*" type="imgfilterdemo.App_Code.imgHandler" path="*.jpeg"/> </httpHandlers> </system.web>