码迷,mamicode.com
首页 > 其他好文 > 详细

MiddleWare中间键实现 简单的防盗链 AOP

时间:2020-04-01 00:44:52      阅读:65      评论:0      收藏:0      [点我收藏+]

标签:director   code   combine   return   方法   aop   erer   this   for   

看了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>();

MiddleWare中间键实现 简单的防盗链 AOP

标签:director   code   combine   return   方法   aop   erer   this   for   

原文地址:https://www.cnblogs.com/hurui1/p/12609712.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!