ASP.NET图片盗链防护指南
图片盗链(Hotlinking)是指其他网站直接链接到你服务器上的图片资源,这会消耗你的带宽和服务器资源。以下是几种在ASP.NET中防止图片盗链的有效方法:
1. 使用URL重写模块(推荐)
在Web.config中配置URL重写规则:
xml
<system.webServer>
<rewrite>
<rules>
<rule name="Prevent Image Hotlinking">
<match url=".*\.(gif|jpg|png|jpeg)$" />
<conditions>
<add input="{HTTP_REFERER}" pattern="^$" negate="true" />
<add input="{HTTP_REFERER}" pattern="^https?://(www\.)?yourdomain\.com" negate="true" />
</conditions>
<action type="Rewrite" url="/images/blocked.png" />
</rule>
</rules>
</rewrite>
</system.webServer>
2. 使用HTTP处理程序(.ashx)
创建一个通用处理程序(ImageHandler.ashx):
csharp
public class ImageHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string imagePath = context.Request.QueryString["img"];
string referrer = context.Request.UrlReferrer?.Host ?? "";
if (string.IsNullOrEmpty(referrer) || !referrer.Contains("yourdomain.com"))
{
context.Response.ContentType = "image/png";
context.Response.WriteFile(context.Server.MapPath("~/images/blocked.png"));
return;
}
string fullPath = context.Server.MapPath(imagePath);
if (File.Exists(fullPath))
{
context.Response.ContentType = "image/" + Path.GetExtension(fullPath).Substring(1);
context.Response.WriteFile(fullPath);
}
}
public bool IsReusable => false;
}
3. 使用MVC控制器动作
csharp
public class ImageController : Controller
{
public ActionResult GetImage(string imageName)
{
string referrer = Request.UrlReferrer?.Host ?? "";
if (string.IsNullOrEmpty(referrer) || !referrer.Contains("yourdomain.com"))
{
return File(Server.MapPath("~/images/blocked.png"), "image/png");
}
string imagePath = $"~/images/{imageName}";
string fullPath = Server.MapPath(imagePath);
if (System.IO.File.Exists(fullPath))
{
string contentType = $"image/{Path.GetExtension(imageName).Substring(1)}";
return File(fullPath, contentType);
}
return HttpNotFound();
}
}
4. 使用.htaccess方法(适用于IIS)
如果你的网站托管在IIS上,可以在web.config中添加:
xml
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="https://www.yourdomain.com" />
</customHeaders>
</httpProtocol>
</system.webServer>
5. 使用C#中间件(ASP.NET Core)
对于ASP.NET Core应用,可以创建中间件:
csharp
public class AntiHotlinkingMiddleware
{
private readonly RequestDelegate _next;
public AntiHotlinkingMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
var path = context.Request.Path.Value;
var isImage = path.EndsWith(".jpg") || path.EndsWith(".png") || path.EndsWith(".gif");
if (isImage)
{
var referer = context.Request.Headers["Referer"].ToString();
if (!string.IsNullOrEmpty(referer) && !referer.Contains("yourdomain.com"))
{
context.Response.ContentType = "image/png";
await context.Response.SendFileAsync(Path.Combine("wwwroot", "images", "blocked.png"));
return;
}
}
await _next(context);
}
}
然后在Startup.cs中注册:
csharp
app.UseMiddleware<AntiHotlinkingMiddleware>();
最佳实践建议
结合多种方法使用,提高防护效果
为合法引用设置白名单而不是黑名单
定期检查服务器日志,监控盗链情况
考虑使用CDN服务,许多CDN提供防盗链功能
对于敏感图片,考虑添加水印或使用低分辨率版本供外部引用