IIS中通过ISAPI根据不同的后缀名将不同的请求交给不同的处理程序,可以在不同版本的framework安装目录的config/web.config查看到各种文件的请求交给的相应处理程序,我可以实现IHttpHandler接口,为特定的文件进行处理。
namespace SafeWebApp
{
public class UrlHandler:IHttpHandler
{
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext context)
{
string stest = context.Request.FilePath;
string filename = context.Server.MapPath(context.Request.FilePath);
if (context.Request.UrlReferrer == null)
{
context.Response.ContentType = "image/JPEG";
context.Response.WriteFile("~/no.jpg");
}
else
{
if (context.Request.UrlReferrer.Host.IndexOf("你的域名") > -1)
{
context.Response.ContentType = "image/JPEG";
context.Response.WriteFile(filename);
}
else
{
context.Response.ContentType = "image/JPEG";
context.Response.WriteFile("~/no.jpg");
}
}
}
}
}
然后在具体站点的web.config中注册这个HttpHandler
<httpHandlers>
<add verb="*" path="*.jpg" type="SafeWebApp.UrlHandler,SafeWebApp"/>
</httpHandlers>
在IIS的站点属性下设置映射
OK,别人现在就不能盗链你的图片了,始终显示no.jpg图片,举一反三,你可以在这里为各种文件进行相应的处理,如下载文件rar等等
ContextType 文件的mime类型,如果你不知道该文件的mime类型,上传该文件,属性中有该值