首页 > 其他分享 >.Net6对AOP的多种支持之IAsyncActionFilter

.Net6对AOP的多种支持之IAsyncActionFilter

时间:2023-02-15 00:55:43浏览次数:40  
标签:IAsyncActionFilter context AOP Action Net6 logger 执行 public

环境:   .Net6    windows10   Web项目  ps:Log4net写入到文件以及写入到数据库中

开发工具: Vs2022

IAsyncActionFilter(日志异步实现)

 

IAsynctionFilter概念

   ASP.NET Core6提供的是接口IAsyncActionFilter/ActionFilterAttribute

系统框架提供的抽象(接口(异步实现)/抽象类),可以是自定义扩展,也可以直接使用

通过一个特性的支持

作用是做日志,更加贴合Action,缓存也能做,但是专人做专事,用它来做日志会更好

 

执行顺序

    实现的接口里有个委托参数,执行这个委托(就是执行Action方法),所以需要以这个委托执行为界限,可在之前或者之后添加

需要执行的。

 

实现IAsyncActionFilter

定义特性类

       名称以Attribute结尾(标记特性时可以省略),继承Attribute、IAsyncActionFilter(并实现该接口)

      public class CustomIActionFilecuting(ActionExecutingContext context)   

这里的执行顺序会是在构造函数执行以后,Action执行之前执行

            

实现接口

            public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)

 执行next委托就会执行Action,以这个委托执行为界限,可在之前或者之后添加

需要执行的。

 

加入特性标记

   在需要做日志的方法上标记特性

        [TypeFilter(typeof(CustomIAsyncActionFilterAttribute))]

        public IActionResult index3(int id ){

            return View();

        }

 

完整Code示例

using Microsoft.AspNetCore.Mvc.Filters;

namespace WebApplication1.Untity.Filters
{

    /// <summary>
    /// 异步ActionFilter
    /// </summary>
    public class CustomIAsyncActionFilterAttribute : Attribute, IAsyncActionFilter
    {


        //构造函数注入
        private readonly ILogger<CustomIAsyncActionFilterAttribute> _logger;
        public CustomIAsyncActionFilterAttribute(ILogger<CustomIAsyncActionFilterAttribute> logger) 
        {
            this._logger = logger;
        }
        
        /// <summary>
        /// 实现接口方法
        /// </summary>
        /// <param name="context"></param>
        /// <param name="next">执行委托就会执行Action</param>
        /// <returns></returns>
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            var para = context.HttpContext.Request.QueryString.Value;
            var controllerName = context.HttpContext.GetRouteValue("controller");
            var actionName = context.HttpContext.GetRouteValue("action");
           
            
            _logger.LogInformation($"执行{controllerName}控制器的{actionName}方法,参数是:{para}");
            Console.WriteLine("之前");

            ActionExecutedContext executedContext = await next.Invoke();//这里就是执行Action
            Console.WriteLine("之后");
            var result = Newtonsoft.Json.JsonConvert.SerializeObject(executedContext.Result);
            _logger.LogInformation($"执行{controllerName}控制器的{actionName}方法,结果是:{result}");

        }
    }
}

 

 

        //[TypeFilter(typeof(CustomIActionFilterAttribute))]
        [TypeFilter(typeof(CustomIAsyncActionFilterAttribute))]
        public IActionResult index3(int id )
        {

            ViewBag.user = Newtonsoft.Json.JsonConvert.SerializeObject(new
            {
                Id = id,
                Name = "John--ViewBag",
                Age = 18
            });

            ViewData["UserInfo"] = Newtonsoft.Json.JsonConvert.SerializeObject(new
            {
                Id = id,
                Name = "John --ViewData",
                Age = 18
            });

            object description = "参数测试啊啊啊啊";

            return View(description);
        }

 

标签:IAsyncActionFilter,context,AOP,Action,Net6,logger,执行,public
From: https://www.cnblogs.com/JohnTang/p/17121340.html

相关文章

  • .NET6+WebApi+Vue 前后端分离后台管理系统(一)
    概述项目是用的NET6webapi搭建一个前后端分离的后端管理框架,项目分为:表示层、业务层、数据访问层、数据存储层。 Common:公共组件层,存放一些公共的方法。Model:实体Mod......
  • .Net Core(.Net6)创建grpc
    1.环境要求.Net6,VisualStudio2019以上官方文档:https://learn.microsoft.com/zh-cn/aspnet/core/tutorials/grpc/grpc-startNetFramework版本:https://www.cnblog......
  • .NET6 API 部署标准流程
    一、安装dotnet环境#第一步:将Microsoft包签名密钥添加到受信任密钥列表,并添加Microsoft包存储库sudorpm-Uvhhttps://packages.microsoft.com/config/centos/7/packa......
  • .Net6 + GraphQL + MongoDb 实现Mutate更新数据
    介绍Query的部分我们讲完了,现在讲一下Mutate(就是操作增修删)本节讲一下修改,删除就不讲了正文publicrecordUpdatePostInput(stringPostId,stringTitle,string......
  • 面试难题:Spring AOP循环依赖,如何解决?
    面试难题:SpringAOP循环依赖,如何解决?问:Spring如何解决循环依赖?答:Spring通过提前曝光机制,利用三级缓存解决循环依赖(这原理还是挺简单的,参考:三级缓存、图解循环依赖原......
  • AOP
    代理分为静态代理和动态代理,静态代理,顾名思义,就是你自己写代理对象,动态代理,则是在运行期,生成一个代理对象。SpringAOP就是基于动态代理的,如果要代理的对象,实现了某个接口,那......
  • AOP切入同类调用方法不起作用,AopContext.currentProxy()帮你解决这个坑
    原来在springAOP的用法中,只有代理的类才会被切入,我们在controller层调用service的方法的时候,是可以被切入的,但是如果我们在service层A方法中,调用B方法,切点切的是B方法,那么......
  • 用注解实现AOP
    一、@Aspect:切面类@Before:前置@Around:环绕@AfterRetuming:后置@AfterThrowing:异常@After:最终@Pointcut:连接点,标注在一个无返、无参、二、加载<context:component-scanbase-p......
  • NET6 IOC 基本流程 ( 蒋金楠书籍)
    准备要注册的对象和接口,以及注册的生命周期准备注册,先检查是否释放检测是否已注册,没有则添加到集合内并返回当前对象GetService根据接口获取对象,判断是否为v容器类还......
  • aop操作-AspectJ注解方式
    1.创建类,类中定义方法packagecom.xxx.spring.aop.aopanno;publicclassUser{publicvoidadd(){System.out.println("add...");}}2.创建增强......