.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>();
        }
    }
}

四、使用中间件

  

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM