(精華)2020年9月17日 ASP.NET Core 中介軟體詳解

愚公搬程式碼發表於2020-09-10

1.基本中介軟體的使用

public static void Start()
{
    var host = Host.CreateDefaultBuilder()
        .ConfigureWebHost(builder => builder
            .UseKestrel()
            .Configure(app => 
                app.Run(context => 
                    context.Response.WriteAsync("Hello!"))
            )
        ).Build();
    host.Run();
}
public static class Sample02
{
    public static void Start()
    {
        var host = Host.CreateDefaultBuilder()
            .ConfigureWebHostDefaults(builder => builder
                .Configure(app => app
                    .Use(Middleware1)
                    .Use(Middleware2)
                )
            ).Build();
        host.Run();
    }

    private static RequestDelegate Middleware1(RequestDelegate next)
    {
        async Task App(HttpContext context)
        {
            await context.Response.WriteAsync("Middleware 1 Begin.");
            await next(context);
            await context.Response.WriteAsync("Middleware 1 End.");
        }
        return App;
    }


    private static RequestDelegate Middleware2(RequestDelegate next)
    {
        async Task App(HttpContext context)
        {
            await context.Response.WriteAsync("Middleware 2 Begin.");
        }
        return App;
    }
}

2.強型別中介軟體的使用

public class Sample03
{
    public class HelloMiddleware : IMiddleware
    {
        public async Task InvokeAsync(HttpContext context, RequestDelegate next)
        {
            await context.Response.WriteAsync("Hello");
        }
    }

    public static void Start()
    {

        var host = Host.CreateDefaultBuilder()
            .ConfigureWebHostDefaults(builder => builder
                .ConfigureServices(collection => collection.AddSingleton<HelloMiddleware>())
                .Configure(app => app
                    .UseMiddleware<HelloMiddleware>()
                )
            ).Build();
        host.Run();
    }
}

3.約定中介軟體的使用

public class Sample04
{
    public class HelloMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly string _content;
        private readonly bool _isToNext;

        public HelloMiddleware(RequestDelegate next, string content, bool isToNext = false)
        {
            _next = next;
            _content = content;
            _isToNext = isToNext;
        }

        public async Task InvokeAsync(HttpContext httpContext)
        {
            await httpContext.Response.WriteAsync($"Hello {_content}!\r\n");
            if (_isToNext) await _next(httpContext);
        }
    }

    public static void Start()
    {

        var host = Host.CreateDefaultBuilder()
            .ConfigureWebHostDefaults(builder => builder
                .Configure(app => app
                    .UseMiddleware<HelloMiddleware>("Rick", true)
                    .UseMiddleware<HelloMiddleware>("Motry")
                )
            ).Build();
        host.Run();
    }
}

4.Startup的由來和使用

public static class Sample06
    {
        public class Startup
        {
            public void ConfigureServices(IServiceCollection services)
            {
                foreach (var service in services)
                {
                    var serviceName = service.ServiceType.Name;
                    var implType = service.ImplementationType;
                    if (implType != null)
                    {
                        Console.WriteLine($"{service.Lifetime, -15}{serviceName,-40}{implType.Name}");
                    }
                }
            }

            public void Configure(IApplicationBuilder app)
            {

            }
        }

        public static void Start()
        {
            var host = Host.CreateDefaultBuilder()
                .ConfigureWebHostDefaults(builder => builder
                    .UseStartup<Startup>())
                .Build();
            
            host.Run();
        }
    }
public class Sample07
    {
        public class Startup
        {
            public Startup(IConfiguration configuration, IHostEnvironment hostingEnvironment)
            {
                Debug.Assert(configuration != null);
                Debug.Assert(hostingEnvironment != null);
            }

            public void ConfigureServices(IServiceCollection services)
            {
            }

            public void Configure(IApplicationBuilder app)
            {
            }
        }

        public static void Start()
        {
            var host = Host.CreateDefaultBuilder()
                .ConfigureWebHostDefaults(builder => builder
                    .UseStartup<Startup>())
                .Build();
            
            host.Run();
        }
    }
public class Sample09
    {

        public class Test1{ };
        public class Test2{ };

        public class TestMiddleware
        {
            private readonly RequestDelegate _next;

            public TestMiddleware(RequestDelegate next, Test1 test1, Test2 test2)
            {
                Debug.Assert(test1 != null);
                Debug.Assert(test2 != null);
                _next = next;
            }

            public async Task InvokeAsync(HttpContext httpContext)
            {
                Debug.Assert(_next != null);
                await httpContext.Response.WriteAsync("Test");

            }
        }

        public class Startup
        {

            public void ConfigureServices(IServiceCollection services)
            {
                services
                    .AddSingleton<Test1>()
                    .AddSingleton<Test2>();
            }

            public void Configure(IApplicationBuilder app)
            {
                app.UseMiddleware<TestMiddleware>();
            }
        }

        public static void Start()
        {
            var host = Host.CreateDefaultBuilder()
                .ConfigureWebHostDefaults(builder => builder
                    .UseStartup<Startup>())
                .Build();
            
            host.Run();
        }
    }
public class Sample10
    {

        public class Test1{ };
        public class Test2{ };

        public class TestMiddleware
        {
            private readonly RequestDelegate _next;

            public TestMiddleware(RequestDelegate next)
            {
                
                _next = next;
            }

            public async Task InvokeAsync(HttpContext httpContext,Test1 test1, Test2 test2)
            {
                Debug.Assert(test1 != null);
                Debug.Assert(test2 != null);
                await httpContext.Response.WriteAsync("Test");

            }
        }

        public class Startup
        {

            public void ConfigureServices(IServiceCollection services)
            {
                services
                    .AddSingleton<Test1>()
                    .AddSingleton<Test2>();
            }

            public void Configure(IApplicationBuilder app)
            {
                app.UseMiddleware<TestMiddleware>();
            }
        }

        public static void Start()
        {
            var host = Host.CreateDefaultBuilder()
                .ConfigureWebHostDefaults(builder => builder
                    .UseStartup<Startup>())
                .Build();
            
            host.Run();
        }
    }
public class Sample11
    {
        public class Test1{ }
        public class Test2{ }       
        public static void Start()
        {
            var host = Host.CreateDefaultBuilder()
                .ConfigureWebHostDefaults(builder => builder
                    .ConfigureServices(collection => collection
                        .AddSingleton<Test1>()
                        .AddSingleton<Test2>()
                        .AddControllersWithViews())
                    .Configure(app=>app
                        .UseRouting()
                        .UseEndpoints(routeBuilder => routeBuilder.MapControllers()))
                )
                .Build();
            
            host.Run();
        }
    }

    public class Startup
    {
        public void Configure(IApplicationBuilder app)
        {

        }

        public void ConfigureServices(IServiceCollection services)
        {

        }
    }

    public class HomeController : Controller
    {
        private readonly Sample11.Test1 _test1;

        public HomeController(Sample11.Test1 test1)
        {
            _test1 = test1;
        }

        [HttpGet("/")]
        public IActionResult Index()
        {
            ViewBag.Test1 = _test1;
            return View();
        }
    }

相關文章