当前位置: 首页 > ai >正文

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提供防盗链功能

对于敏感图片,考虑添加水印或使用低分辨率版本供外部引用

http://www.xdnf.cn/news/2356.html

相关文章:

  • Java接口默认方法冲突
  • 2025.4.27_C_Struct,Enum,Union
  • 单片机学习笔记9.数码管
  • Redis使用总结
  • 相机DreamCamera2录像模式适配尺寸
  • 使用c++实现一个简易的量子计算,并向外提供服务
  • 一文说清Token这个大模型中的数字乐高积木的作用
  • MIT6.S081 - Lab10 mmap(文件内存映射)
  • 内耗型选手如何能做到不内耗?
  • MySQL最新安装、连接、卸载教程(Windows下)
  • Linux进程学习【环境变量】进程优先级
  • T8332FN凯钰LED驱动芯片多拓扑车规级AEC-Q100
  • 秒杀压测计划 + Kafka 分区设计参考
  • IP地址与子网计算工具
  • 0302洛必达法则-微分中值定理与导数的应用.md
  • 云原生课程-Docker
  • openstack创建虚拟机
  • 什么是模块化区块链?Polkadot 架构解析
  • 在Linux中,使用标准IO库,进行格式化IO操作
  • 深度解析Zemax优化函数:让光学设计从“能用”到“极致”的核心密码
  • 驱动开发硬核特训 · Day 22(下篇): # 深入理解 Power-domain 框架:概念、功能与完整代码剖析
  • I-CON: A Unifying Framework for Representation Learning
  • qt 3d航迹图
  • Scala集合操作与WordCount案例实战总结
  • Linux高效IO
  • SQL面试之--明明建了索引为什么失效了?
  • docker部署ruoyi系统
  • Rule.resourceQuery(通过路径参数指定loader匹配规则)
  • 【音视频】FFmpeg过滤器框架分析
  • django.db.models.query_utils.DeferredAttribute object