1 using System.Threading.Tasks;
2 using Microsoft.AspNetCore.Hosting;
3 using Microsoft.AspNetCore.Http;
4 using Microsoft.Extensions.Hosting;
5
6 namespace ConsoleApp2
7 {
8 public static class Sample02
9 {
10
11 public static void Start()
12 {
13
14 var host = Host.CreateDefaultBuilder()
15 .ConfigureWebHostDefaults(builder => builder
16 .Configure(app => app
17 .Use(Middleware1) //使用中间件
18 .Use(Middleware2)
19 )
20 ).Build();
21 host.Run();
22 }
23
24 private static RequestDelegate Middleware1(RequestDelegate next)
25 {
26 async Task App(HttpContext context)
27 {
28 await context.Response.WriteAsync("Middleware 1 Begin."); //Step 1
29 await next(context); //跳转到下一个中间件
30 await context.Response.WriteAsync("Middleware 1 End."); //Step3
31 }
32
33 return App;
34 }
35
36
37 private static RequestDelegate Middleware2(RequestDelegate next)
38 {
39 async Task App(HttpContext context)
40 {
41 await context.Response.WriteAsync("Middleware 2 Begin."); //没有就返回 //Step2
42 }
43
44 return App;
45 }
46 }
47 }
![]()