看了Elevent老师的视频,把方法记一下
public class RefuseStealingMiddleWare { private readonly RequestDelegate next; public RefuseStealingMiddleWare(RequestDelegate next) { this.next = next; } public async Task Invoke(HttpContext context) { string url = context.Request.Path.Value; if (!url.Contains(".png")) { await next(context);//正常流程 return; } string urlReferrer = context.Request.Headers["Referer"]; if (string.IsNullOrWhiteSpace(urlReferrer))//直接访问的图片 { await this.SetForbiddenImage(context); } else if (!urlReferrer.Contains("localhost"))//这里是举例子用的localhost { await this.SetForbiddenImage(context); } else { await next(context);//正常流程 } } /// <summary> /// 设置拒绝图片 /// </summary> /// <param name="context"></param> /// <returns></returns> private async Task SetForbiddenImage(HttpContext context) { string defaultImagePath = "wwwroot/image/menuDish.png"; 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); } }
在startup的configure方法加上
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { //防止盗链 app.UseMiddleware<RefuseStealingMiddleWare>();
原文地址:https://www.cnblogs.com/hurui1/p/12609712.html
时间: 2024-10-17 18:33:04