XingDy姐

中间件

电脑版发表于:2019/12/24 11:22

今天我们记录一下中间件 ,看到下面那些代码, 我们就知道了:


 // 处理静态文件中间件
            app.UseStaticFiles();
            app.UseCookiePolicy();
            // 启动ids4中间件
            app.UseIdentityServer();
            // 使用自己的中间件
            app.UseMyIp();
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

我们弄一个类,写自己的中间件如:


public class MyIPMiddleware
    {
        private readonly RequestDelegate _next;
        // 写日志
        private readonly ILogger _logger;
        public MyIPMiddleware(RequestDelegate next, ILoggerFactory logger)
        {
            _next = next;
            _logger = logger.CreateLogger<MyIPMiddleware>();
        }
        /// <summary>
        /// 执行的方法
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task Invoke(HttpContext context)
        {
            _logger.LogWarning("执行自己的中间件,获取IP地址.....");
            //执行超作
            _logger.LogError("My Ip:" + context.Connection.RemoteIpAddress.ToString());
            //执行下一个中间件
            await _next.Invoke(context);
        }
    }


我们可以为了看着厉害一点,我们还可以在写一个类来封装它:


public static IApplicationBuilder UseMyIp(this IApplicationBuilder app)
        {
            //链式编程
            return app.UseMiddleware<MyIPMiddleware>();
        }

这样我们自己写的中间件和官方的一样了....

关于TNBLOG
TNBLOG,技术分享。技术交流:群号677373950
ICP备案 :渝ICP备18016597号-1
App store Android
精彩评论
{{item.replyName}}
{{item.content}}
{{item.time}}
{{subpj.replyName}}
@{{subpj.beReplyName}}{{subpj.content}}
{{subpj.time}}
猜你喜欢