asp.net文件防盗链

URLRewriter实现

可以参考下面的文章

代码

.net framework

新建asp.net framework的web项目,新建AntiTheftChainHandler

using System.Web;

namespace AntiTheftChainStu01.Handler
{
    public class AntiTheftChainHandler : IHttpHandler
    {
        public bool IsReusable => true;

        /// <summary>
        /// jpg文件防盗链
        /// </summary>
        /// <param name="context"></param>
        public void ProcessRequest(HttpContext context)
        {
            string FileName = context.Server.MapPath(context.Request.FilePath);
            string notFoundFile = context.Server.MapPath("/404.jpg");
            if (context.Request.UrlReferrer ==null|| context.Request.UrlReferrer.Host == null)
            {
                context.Response.ContentType = "image/JPEG";
                context.Response.WriteFile(notFoundFile);
            }
            else
            {
                //此处的可填你网站的域名,因为我这里采用的是本机演示,故使用localhost
                if (context.Request.UrlReferrer.Host.IndexOf("localhost") != -1)
                {
                    context.Response.ContentType = "image/JPEG";
                    context.Response.WriteFile(FileName);
                }
                else
                {
                    context.Response.ContentType = "image/JPEG";
                    context.Response.WriteFile(notFoundFile);
                }
            }
        }
    }
}

修改web.config

<system.webServer>
	<!-- 确保所有请求都经过ASP.NET的管道处理 -->
	<modules runAllManagedModulesForAllRequests="true" />
	<handlers>
		<add name="jpgHandler" path="*.jpg" verb="*" type="AntiTheftChainStu01.Handler.AntiTheftChainHandler,AntiTheftChainStu01" />
	</handlers>
	<!--设置默认起始页面-->
	<defaultDocument>
		<files>
			<clear />
			<add value="Index.aspx" />
		</files>
	</defaultDocument>
</system.webServer>

新建测试的html

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <img src="http://localhost:63099/image/imgs/002.jpg" alt="">
</body>
</html>

最后效果如下
在这里插入图片描述
微信公众号图片也是实现的类似的效果
在这里插入图片描述

.net core

新建中间件RefuseStealingMiddleWare

namespace AntiTheftChainStu02
{
    public class RefuseStealingMiddleWare
    {
        private readonly RequestDelegate _next;

        public RefuseStealingMiddleWare(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            string url = context.Request.Path.Value;
            if (!url.Contains(".jpg"))
            {
                await _next(context);//走正常流程
                return;
            }

            string urlReferrer = context.Request.Headers["Referer"];
            if (string.IsNullOrWhiteSpace(urlReferrer))//直接访问
            {
                await this.SetForbiddenImage(context);//返回404图片
            }
            else if (!urlReferrer.Contains("localhost"))//非当前域名
            {
                await this.SetForbiddenImage(context);//返回404图片
            }
            else
            {
                await _next(context);//走正常流程
            }
        }
        /// <summary>
        /// 设置拒绝图片
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private async Task SetForbiddenImage(HttpContext context)
        {
            string defaultImagePath = "wwwroot/404.jpg";
            string path = Path.Combine(Directory.GetCurrentDirectory(), defaultImagePath);

            FileStream fs = File.OpenRead(path);
            byte[] bytes = new byte[fs.Length];
            await fs.ReadAsync(bytes, 0, bytes.Length);
            await context.Response.Body.WriteAsync(bytes, 0, bytes.Length);
        }
    }
}

修改Program.cs

namespace AntiTheftChainStu02
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);
            var app = builder.Build();

            app.UseMiddleware<RefuseStealingMiddleWare>();
            app.UseDefaultFiles();
            app.UseStaticFiles();
            

            app.Run();
        }
    }
}

新建index.html

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <img src="https://localhost:7229/image/imgs/001.jpg" alt="">
</body>
</html>

在这里插入图片描述

参考

https://cloud.tencent.com/developer/article/1459550
https://www.cnblogs.com/mbskys/articles/633043.html
https://blog.youkuaiyun.com/net_programmer1/article/details/136627093
https://blog.youkuaiyun.com/weixin_42084199/article/details/110874803

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

假装我不帅

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值