.NetCore 中间件学习

Fork Me On Github

中间件类写法

    public class TestMiddleware
    {
        private readonly RequestDelegate _next;

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

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

注册到宿主上


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

使用

Startup.cs


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

内联中间件

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

vs 2017 使用中间件模板

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

Click here to view
0 264 0