.net core 学习笔记(2)-中间件

小项目中有个操作日志的功能,主要是记录用户对修改数据的操作进行记录,记录的内容包括 访问的控制器和方法,以及控制器方法中接收的参数,操作用户,及操作IP等信息,最开始是用ActionFilterAttributes实现的,因为犯了个傻,想用中间件去实现,就查了资料,写了个很简单的。主要包括三步

一、定义中间件

//中间件 
public class LogwriteMiddleware
    {
        private readonly RequestDelegate _next;
        private IUsyOperationLogService _usyoperationlogservice;

        public LogwriteMiddleware(IUsyOperationLogService usyoperationlogservice, RequestDelegate next)
        {
            _usyoperationlogservice = usyoperationlogservice;
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            var path = context.Request.Path;//执行操作前
            // await _next.Invoke(context);
            await _next.Invoke(context);
           //执行操作后
        }
    }

  二、往ApplicationBuilder中添加我们自定义的中间件

//往ApplicationBuilder中添加我们自定义的中间件
public static class LogwriteExtensions
    {
        public static IApplicationBuilder UseLogWrite(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<LogwriteMiddleware>();
        }
       
    }

三、startup的Configure中注册我们的中间件:这个UseLogWrite就是上面定义的LogwriteExtensions

添加中间件的方法名

 app.UseLogWrite();  

磕磕绊绊写完个中间件,调试的时候发现在invoke 方法中,根本取不到我们写日志需要的控制器方法,及参数等信息

上网查资料,认真阅读了几篇大牛的博客,才知道真是犯了个傻,中间件是拦截不到控制器操作的上下文的,所有在中间件中无法获取到传递给控制器的参数

附上几篇好文的链接

http://www.cnblogs.com/savorboard/p/5586229.html

http://www.cnblogs.com/dotNETCoreSG/p/aspnetcore-3_2-middleware.html

原文地址:https://www.cnblogs.com/huanglin101/p/6208299.html