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

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

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

相关文章:

  • 总线位宽不变,有效数据位宽变化的缓存方案
  • 概率论与统计(不确定性分析)主要应用在什么方面?涉及到具体知识是什么?
  • 深入解析 npm 与 Yarn:Node.js 包管理工具对比与选型指南
  • 考研系列-计算机组成原理第五章、中央处理器
  • Spring Cloud Stream喂饭级教程【搜集全网资料整理】
  • 【Fifty Project - D18】
  • 【Flutter】Unity 三端封装方案:Android / iOS / Web
  • NGINX `ngx_http_core_module` 深度解读与实战指南
  • 晶晨S905L/LB芯片_安卓11.0_已适配移动遥控_支持外置网卡_支持IPV6_通刷线刷包
  • 通过ThreadLocal存储登录用户信息
  • rt-linux下的D状态的堆栈抓取及TASK_RTLOCK_WAIT状态
  • 使用 OpenCV 和 dlib 进行人脸检测
  • ElasticSearch从入门到精通-覆盖DSL操作和Java实战
  • Flutter 学习之旅 之 flutter 有时候部分手机【TextField】无法唤起【输入法软键盘】的一些简单整理
  • 【玩转 JS 函数式编程_016】DIY 实战:巧用延续传递风格(CPS)重构倒计时特效逻辑
  • 【HarmonyOS 5】鸿蒙检测系统完整性
  • 解决 Elasticsearch 启动错误:failed to obtain node locks
  • OpenSPG/KAG v0.7.1 发布, 针对新版若干优化和BUGFIX
  • DeepSeek智能时空数据分析(五):基于区域人口数量绘制地图散点-大模型搜集数据NL2SQL加工数据
  • 新能源汽车运动控制器核心芯片选型与优化:MCU、DCDC与CANFD协同设计
  • 商超展销延长、专区专柜亮相……上海“外贸拓内销”商品与市民见面
  • 传染病防治法修订草案提请三审,拟加强医疗机构疾控能力建设
  • 清华成立人工智能医院,将构建“AI+医疗+教育+科研”闭环
  • 中国平安一季度净赚270亿降逾26%,营运利润增2.4%
  • 李彦宏:DeepSeek不是万能,多模态将是未来基础模型的标配
  • 11-13世纪的地中海贸易