.net core2.0 自定义中间件
一、中间件(Middleware)
中间件是被组装成一个应用程序管道来处理请求和响应的软件组件。
二、编写SimpleMiddleware
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | 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
用起来总有点奇怪,居然不是继承一个基类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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>(); } } } |
四、使用中间件
本文作者:WangJunZzz
本文链接:https://www.cnblogs.com/WangJunZzz/p/8708360.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
分类:
.NETCore
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步