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>();
  • 相关阅读:
    [luogu p1996] 约瑟夫问题
    [luogu p1098] 字符串的展开
    [luogu p1035] 级数求和
    [luogu p1004] 方格取数
    [luogu p3383]【模板】线性筛素数
    [luogu p1223] 排队接水
    [luogu p1002] 过河卒
    [luogu p1001] A+B Problem
    Java BIO/NIO(Non-blocking I/O)详解
    Linux页框&伙伴算法以及slab机制
  • 原文地址:https://www.cnblogs.com/hurui1/p/12609712.html
Copyright © 2011-2022 走看看