.net core 中間件的使用

1:Startup 類 Configure 方法添加中間件

	public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseMyStaticImg();

            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Hello World!");
            });
        }

2:新建類 MyStaticImgExtensions

    public static  class MyStaticImgExtensions
    {
        public static IApplicationBuilder UseMyStaticImg(this IApplicationBuilder app)
        {
            if (app == null)
            {
                throw new ArgumentNullException("app");
            }
            return UseMiddlewareExtensions.UseMiddleware<MyStaticImgMiddleware>(app, Array.Empty<object>());
        }
    }

3:新建類 MyStaticImgMiddleware

    public class MyStaticImgMiddleware
    {
        private readonly RequestDelegate _next;

        public MyStaticImgMiddleware(RequestDelegate next)
        {
            this._next = next;
        }

        /// <summary>
        /// 中間件被調用的時候執行
        /// </summary>
        /// <param name="context">http請求</param>
        /// <returns></returns>
        public Task Invoke(HttpContext context)
        {
            //請求的路徑
            var path = context.Request.Path.Value;
            //如果請求中有png圖片,返回圖片
            if (path.Contains(".png"))
            {
                var mypath = path.TrimStart('/');
                //返回一張圖片
                return context.Response.SendFileAsync(mypath);
            }


            var task = this._next(context);

            return task;
        }
    }

4:注意

圖片的屬性要設置爲始終複製
在這裏插入圖片描述

發佈了10 篇原創文章 · 獲贊 3 · 訪問量 4913
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章