.net core2.0 自定义中间件

一、中间件(Middleware)

  中间件是被组装成一个应用程序管道来处理请求和响应的软件组件。

  

二、编写SimpleMiddleware

using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace GrabNovelApi.MiddleWare
{
    public class SimpleMiddleWare
    {
        private readonly RequestDelegate _next;

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

        public async Task Invoke(HttpContext context)
        {

            Console.WriteLine("invoke");
            await _next.Invoke(context);
        }
    }
}

三、再新建一个:SimpleMiddleWareExtensions.cs

  用起来总有点奇怪,居然不是继承一个基类

using Microsoft.AspNetCore.Builder;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace GrabNovelApi.MiddleWare
{
    public static class SimpleMiddleWareExtensions
    {
        public static IApplicationBuilder SimpleMiddleWare(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<SimpleMiddleWare>();
        }
    }
}

四、使用中间件

  

 

posted @ 2018-04-03 14:39  WangJunZzz  阅读(1156)  评论(0编辑  收藏  举报