• 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>();
  • 相关阅读:
    决策表
    边界值
    等价类
    python_安装python2.7.7和easy_install
    网络_系统测试方案
    软件测试之魂_测试方案模板
    初识HTTP协议web开发
    Bootstrap框架
    jQuery快速入门
    前端基础之BOM和DOM
  • 原文地址:https://www.cnblogs.com/hurui1/p/12609712.html
Copyright © 2020-2023  润新知