zoukankan      html  css  js  c++  java
  • 简单的Asp.net core管道模拟

    简单的管道模拟

    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Threading.Tasks;
    using static ConsolePipeline.Program;
    using System.Linq;
    
    namespace ConsolePipeline
    {
        public class Program
        {
            public delegate Task RequestDelegate(Httpcontext httpcontext);
            static void Main(string[] args)
            {
                ApplicationBuilder app = new ApplicationBuilder();
                app.Use(async (context, next) =>
                {
                    Console.WriteLine("第一次 开始。。。");
                    await next();
                    Console.WriteLine("第一次 结束。。。");
                });
                app.Use(async (context, next) =>
                {
                    Console.WriteLine("第二次 开始。。。");
                    await next();
                    Console.WriteLine("第二次 结束。。。");
                });
                var firstmiddleware = app.Build();
                firstmiddleware(new Httpcontext());
                Console.WriteLine("Hello World!");
            }
        }
    
        public class Httpcontext { }
    
        public class ApplicationBuilder
        {
            //中间的委托,不是中间件
            public static readonly IList<Func<RequestDelegate, RequestDelegate>> _components = new List<Func<RequestDelegate, RequestDelegate>>();
    
            //原生Use
            public ApplicationBuilder Use(Func<RequestDelegate, RequestDelegate> middleware)
            {
                _components.Add(middleware);
                return this;
            }
    
            // 扩展Use
            public ApplicationBuilder Use(Func<Httpcontext, Func<Task>, Task> middleware)
            {
                return Use(next =>
                {
                    return context =>
                    {
                        Task SimpleNext() => next(context);
                        return middleware(context, SimpleNext);
                    };
                });
            }
    
            public RequestDelegate Build()
            {
                RequestDelegate app = next =>
                {
                    Console.WriteLine("中间中间件。。。");
                    return Task.CompletedTask;
                };
    
                foreach (var component in _components.Reverse())
                {
                    app = component(app);
                }
                return app;
            }
        }
    }

    运行效果:

  • 相关阅读:
    tomcat 远程部署项目
    Maven的使用
    FTP服务器的使用
    2017.10-2018.10工作思考
    Java面试题准备(二)
    移植数据库的心得
    重新安装开发环境之安装使用plsql碰到的两个问题
    Redis学习笔记(一)
    开发之没沟通误删客户数据库数据之找数据路
    Java面试准备(一)
  • 原文地址:https://www.cnblogs.com/1175429393wljblog/p/12302074.html
Copyright © 2011-2022 走看看