中间件

internal class Program
{
    static async Task Main(string[] args)
    {
        var appBuilder = new AppBuilder();

        appBuilder.Use(next =>
        {
            return async context =>
            {
                Console.WriteLine("中间件1 开始");
                await next(context);
                Console.WriteLine("中间件1 结束");
            };
        });

        appBuilder.Use(next =>
        {
            return async context =>
            {
                Console.WriteLine("中间件2 开始");
                //await next(context);
                Console.WriteLine("中间件2 结束");
            };
        });

        var app = appBuilder.Build();
        await app(new HttpContext());

        Console.ReadLine();
    }
}

public class HttpContext
{

}

public delegate Task RequestDelegate(HttpContext context);

public class AppBuilder
{
    private IList<Func<RequestDelegate, RequestDelegate>> _components = new List<Func<RequestDelegate, RequestDelegate>>();

    public AppBuilder Use(Func<RequestDelegate, RequestDelegate> middleware)
    {
        _components.Add(middleware);
        return this;
    }

    public RequestDelegate Build()
    {
        RequestDelegate app = context =>
        {
            Console.WriteLine("404");
            return Task.CompletedTask;
        };

        foreach (var component in _components.Reverse())
        {
            app = component(app);
        }

        return app;
    }
}
posted @ 2024-09-03 10:25  pojianbing  阅读(2)  评论(0编辑  收藏  举报