zoukankan      html  css  js  c++  java
  • MiddleWare中间键实现 简单的防盗链 AOP

    看了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>();
  • 相关阅读:
    OCP-1Z0-053-200题-91题-667
    OCP-1Z0-053-200题-92题-668
    OCP-1Z0-053-200题-93题-669
    OCP-1Z0-053-200题-94题-670
    OCP-1Z0-053-200题-96题-671
    OCP-1Z0-053-200题-97题-227
    OCP-1Z0-053-200题-98题-242
    OCP-1Z0-053-200题-99题-10
    在Visual Studio 2010中配置VC++目录
    OCP-1Z0-053-200题-100题-69
  • 原文地址:https://www.cnblogs.com/hurui1/p/12609712.html
Copyright © 2011-2022 走看看