zoukankan      html  css  js  c++  java
  • 任务29:自己动手构建RequestDelegate管道

    cmd创建一个控制台应用程序

    dotnet new console --name MyPipeline

    用VSCode打开这个项目

     新建类RequestDelegate.cs的类文件复制Program里面的代码到RequestDelegate里面代码修改

    引入命名空间。

    创建一个delegaet 叫做 RequestDelegate

    为了演示用,新建一个Context.cs

    完善RequestDelegate

    新建一个List接收一个RequestDelegate返回一个Delegate

    public static List<Func<RequestDelegate,RequestDelegate>> _list=new List<Func<RequestDelegate, RequestDelegate>>();

    模拟我们的ApplicationBuilder里面的方法新建Use的方法,接受一个Func里面接受一个RequestDelegate返回一个RequestDelegate

      public static void Use(Func<RequestDelegate, RequestDelegate> middleware)
      {
         _list.Add(middleware);
      }
    using System;
    using System.Collections.Generic;
    using System.Threading.Tasks;
    

    namespace MyPipeline
    {
    class Program
    {
    public static List<Func<RequestDelegate,RequestDelegate>> _list=new List<Func<RequestDelegate, RequestDelegate>>();
    static void Main(string[] args)
    {
    Use(next
    =>{
    return context=>{
    Console.WriteLine(
    "1");
    return next.Invoke(context);
    //return Task.CompletedTask;
    };
    });
    Use(next
    =>{
    return context=>{
    Console.WriteLine(
    "2");
    return next.Invoke(context);
    };
    });

            RequestDelegate end</span>= (context)=&gt;<span style="color: #000000;">{
                Console.WriteLine(</span><span style="color: #800000;">"</span><span style="color: #800000;">end.....</span><span style="color: #800000;">"</span><span style="color: #000000;">);
                </span><span style="color: #0000ff;">return</span><span style="color: #000000;"> Task.CompletedTask;
            };
            _list.Reverse();</span><span style="color: #008000;">//</span><span style="color: #008000;">顺序反转</span>
            <span style="color: #0000ff;">foreach</span>(<span style="color: #0000ff;">var</span> middleware <span style="color: #0000ff;">in</span><span style="color: #000000;"> _list)
            {
                end</span>=<span style="color: #000000;">middleware.Invoke(end);
            }
    
           
            end.Invoke(</span><span style="color: #0000ff;">new</span><span style="color: #000000;"> Context());
            Console.ReadLine();
        }
    
        </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> <span style="color: #0000ff;">void</span> Use(Func&lt;RequestDelegate, RequestDelegate&gt;<span style="color: #000000;"> middleware)
        {
            _list.Add(middleware);
        }
    
    }
    

    }

    Program.cs

     dotnet run 执行

    执行到1 没有再往下执行

    以上就是整个Http管道的构成过程

  • 相关阅读:
    引用传参
    VS2017 用MySQL Connector 链接 MySQL时 getString异常问题
    Matlab学习日记第3天
    Matlab学习日记第2天
    Matlab学习日记第1天
    c#加密解密方法
    DataGridView添加行号
    c#带参数数组链接数据库方法
    2021/5/27
    2021/5/14
  • 原文地址:https://www.cnblogs.com/owenzh/p/11306997.html
Copyright © 2011-2022 走看看