.NetCore 中间件学习

Fork Me On Github

中间件类写法

c#
                
    public class TestMiddleware
    {
        private readonly RequestDelegate _next;

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

        public Task Invoke(HttpContext httpContext)
        {
            // TO DO
            return _next(httpContext);
        }
    }
12345678910111213141516

注册到宿主上

c#
         

    public static class TestMiddlewareExtensions
    {
        public static IApplicationBuilder UseTestMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<TestMiddleware>();
        }
    }
123456789

使用

Startup.cs

c#
       

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    //app.Use<TestMiddleware>();
    app.UseTestMiddleware();
}
1234567

内联中间件

c#
         
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.Use(async (context, next) =>
    {
        // TO DO
        await next();
    });
}
123456789

vs 2017 使用中间件模板

右键项目》添加》新建项》已安装》ASP.NET Core》WEB》ASP.NET》中间件类

点击查看全文
0 318 0