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.csdn.net/net_programmer1/article/details/136627093
https://blog.csdn.net/weixin_42084199/article/details/110874803