码迷,mamicode.com
首页 > Web开发 > 详细

模拟.net core中间件执行顺序

时间:2020-06-16 23:23:04      阅读:83      评论:0      收藏:0      [点我收藏+]

标签:adl   next   generic   set   names   ons   static   action   public   

using System;
using System.Collections.Generic;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            App app = new App();
            app.Use(next => {
                Console.WriteLine(1);
                return act => {
                    Console.WriteLine("1-before");
                    //其它逻辑代码...
                    Console.WriteLine(act.Url);
                    next.Invoke(act);
                    //其它逻辑代码...
                    Console.WriteLine("1-after");
                };
            });
            app.Use(next => {
                Console.WriteLine(2);
                return act => {
                    Console.WriteLine("2-before");
                    //其它逻辑代码...
                    next.Invoke(act);
                    //其它逻辑代码...
                    Console.WriteLine("2-after");
                };
            });
            app.Use(next => {
                Console.WriteLine(3);
                return act => {
                    Console.WriteLine("3-before");
                    //其它逻辑代码...
                    next.Invoke(act);
                    //其它逻辑代码...
                    Console.WriteLine("3-after");
                };
            });
            Action<HttpContext> act=  app.Builder();

            HttpContext httpContext = new HttpContext();
            act.Invoke(httpContext);

            Console.ReadLine();
        }
    }


    public class App
    {
        List<Func<Action<HttpContext>, Action<HttpContext>>> list = new List<Func<Action<HttpContext>, Action<HttpContext>>>();

        public void Use(Func<Action<HttpContext>, Action<HttpContext>> func)
        {
            list.Add(func);
        }

        public Action<HttpContext> Builder()
        {
            //当集合为空时执行,相当于.net core 下的404
            Action<HttpContext> action = act => { Console.WriteLine("404"); };
            list.Reverse();
            foreach (Func<Action<HttpContext>, Action<HttpContext>> item in list)
            {
                action = item.Invoke(action);
            }
            return action;
        }
    }

    public class HttpContext
    {
        public int Id { get; set; }
        public string Url { get; set; } = "http://www.baidu.com";
        public string Host { get; set; } = "www.baidu.com";
    }
}

 

模拟.net core中间件执行顺序

标签:adl   next   generic   set   names   ons   static   action   public   

原文地址:https://www.cnblogs.com/slwangzi/p/13149675.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!