本文地址:http://www.cnblogs.com/yizhyi/admin/javascript:;
using System;
using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; using System.Globalization; using System.IO; namespace HttpHandler { public class ImageHandler:IHttpHandler { #region IHttpHandler 成员 public void ProcessRequest(HttpContext context) { HttpRequest req = context.Request; string IMG_path = req.PhysicalPath; string contentType; 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.gif"); } 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; } } #endregion private string GetContentType(string path) { string extension = Path.GetExtension(path); string type; switch (extension) { case ".gif": type = "image/gif"; break; case ".jpg": type = "image/Jpeg"; break; case ".png": type = "image/png"; break; default: type = ""; break; } return type; } } } web.config <add verb="*" path="*.jpg" type="HttpHandler.ImageHandler, HttpHandler"/> <add verb="*" path="*.gif" type="HttpHandler.ImageHandler, HttpHandler"/> <add verb="*" path="*.png" type="HttpHandler.ImageHandler, HttpHandler"/> |