本文使用.NET Core 3.1.
准备两张图片:
编写一个OuterImgMiddleware中间件,编写如下代码:
private readonly RequestDelegate _next;
private readonly IWebHostEnvironment _webHostEnvironment;
public OuterImgMiddleware(RequestDelegate next, IWebHostEnvironment webHostEnvironment)
{
_webHostEnvironment = webHostEnvironment;
_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, _webHostEnvironment);//返回404图片
}
else if (!urlReferrer.Contains("localhost"))//非当前域名
{
await this.SetForbiddenImage(context, _webHostEnvironment);//返回404图片
}
else
{
await _next(context);//走正常流程
}
}
/// <summary>
/// 设置拒绝图片
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
private async Task SetForbiddenImage(HttpContext context, IWebHostEnvironment webHostEnvironment)
{
string defaultImagePath = webHostEnvironment.WebRootPath+ "\\Error\\404.jpg";// "wwwroot/Document/Img/Forbidden.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);
}
启动中间件。需要注意的是, app.UseMiddleware<OuterImgMiddleware>()应至于 app.UseStaticFiles();之前