当前位置: 首页 > article >正文

ABP框架9——自定义拦截器的实现与使用

一、AOP编程

  • AOP定义:面向切片编程,着重强调功能,将功能从业务逻辑分离出来。
  • AOP使用场景:处理通用的、与业务逻辑无关的功能(如日志记录、性能监控、事务管理等)
  • 拦截器:拦截方法调用并添加额外的行为,比如日志记录、权限检查等
  • 拦截器是 AOP 编程的一种实现方式

二、拦截器在ABP框架中的写法位置

1.在应用层-拦截器文件夹编写拦截器

2.在应用层-相应模块类注册拦截器

三、版本一(不推荐,ABP封装拦截器)

不推荐是因为很多功能都不支持,比如说查特性、查路由、接口名称等,不过捕捉日志还是可以的!

1.应用层

using Acme.BookStore.Books;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.DependencyInjection;
using Volo.Abp.DynamicProxy;

namespace Acme.BookStore.Interceptor
{
    //应用层
    public class AopInterceptor : AbpInterceptor, ITransientDependency
    {
        public override async Task InterceptAsync(IAbpMethodInvocation invocation)
        {
            try
            {
                //入参
                var arguments = invocation.Arguments;

                // 在方法执行前输出日志
                Trace.WriteLine($"【调用方法】: {invocation.Method.Name},【时间】{DateTime.Now},【入参】: {string.Join(",", arguments)}");

                // 继续执行原方法
                await invocation.ProceedAsync();
                var returnValue = invocation.ReturnValue;
                // 在方法执行后输出日志
                Trace.WriteLine($"方法执行完成,出参数【{returnValue}】");
            }
            catch (Exception ex)
            {
                // 模拟捕捉错误并输出日志
                Trace.WriteLine($"方法 {invocation.Method.Name} 执行发生错误: {ex.Message}, {DateTime.Now}");
            }
        }
    }

}

2.模块类

using Acme.BookStore.Interceptor;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using System;
using System.Diagnostics;
using System.Linq;
using Volo.Abp.Account;
using Volo.Abp.AutoMapper;
using Volo.Abp.DependencyInjection;
using Volo.Abp.DynamicProxy;
using Volo.Abp.FeatureManagement;
using Volo.Abp.Identity;
using Volo.Abp.Json;
using Volo.Abp.Json.SystemTextJson;
using Volo.Abp.Modularity;
using Volo.Abp.PermissionManagement;
using Volo.Abp.SettingManagement;
using Volo.Abp.TenantManagement;
using Volo.Abp.Uow;

namespace Acme.BookStore;

[DependsOn(
    typeof(BookStoreDomainModule),
    typeof(AbpAccountApplicationModule),
    typeof(BookStoreApplicationContractsModule),
    typeof(AbpIdentityApplicationModule),
    typeof(AbpPermissionManagementApplicationModule),
    typeof(AbpTenantManagementApplicationModule),
    typeof(AbpFeatureManagementApplicationModule),
    typeof(AbpSettingManagementApplicationModule)
    )]
public class BookStoreApplicationModule : AbpModule
{
    public override void ConfigureServices(ServiceConfigurationContext context)
    {
        Configure<AbpAutoMapperOptions>(options =>
        {
            options.AddMaps<BookStoreApplicationModule>();
        });

        // 注册拦截器
        context.Services.OnRegistred(ctx =>
        {
            if (ctx.Interceptors.Any())
            {
                ctx.Interceptors.TryAdd<AopInterceptor>();
            }
        });
    }
}

四、版本二(推荐 MVCcore过滤器)

1.应用层

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Diagnostics;
using System.Linq;
using Volo.Abp.DependencyInjection;

namespace Acme.BookStore.Interceptor
{
    //应用层
    public class AopInterceptor : IActionFilter, ITransientDependency 
    {
        /// <summary>
        /// 请求之前
        /// </summary>
        /// <param name="context"></param>
        public void OnActionExecuting(ActionExecutingContext context)
        {
            //方法名称
            var methodName = (context.ActionDescriptor as ControllerActionDescriptor)?.ActionName;
            // 特性
            var arrt = context.ActionDescriptor.EndpointMetadata.OfType<Attribute>();
            //判断是否含有某个特性标签
            bool hasMyCustomAttribute = arrt.Any(attr => attr.GetType() == typeof(AopAttribute));
            Trace.WriteLine($"执行前:【路由】{context.ActionDescriptor.AttributeRouteInfo?.Template},【方法】{methodName},【入参】{context?.ActionArguments},【特性】{arrt},【请求方式】{context.HttpContext.Request.Method}");
        }

        /// <summary>
        /// 请求之后
        /// </summary>
        /// <param name="context"></param>
        public void OnActionExecuted(ActionExecutedContext context)
        {
            var res = context.Result as ObjectResult;
            Trace.WriteLine($"执行后:【出参】{res?.Value}");
        }
    }

    /// <summary>
    /// 自定义特性标签(可选)
    /// </summary>
    [AttributeUsage(AttributeTargets.Interface | AttributeTargets.Class | AttributeTargets.Method)]
    public class AopAttribute : Attribute { }
}

2.模块类

using Acme.BookStore.Interceptor;
using Microsoft.Extensions.DependencyInjection;
using Volo.Abp.Account;
using Volo.Abp.AutoMapper;
using Volo.Abp.FeatureManagement;
using Volo.Abp.Identity;
using Volo.Abp.Json;
using Volo.Abp.Modularity;
using Volo.Abp.PermissionManagement;
using Volo.Abp.SettingManagement;
using Volo.Abp.TenantManagement;


namespace Acme.BookStore;

[DependsOn(
    typeof(BookStoreDomainModule),
    typeof(AbpAccountApplicationModule),
    typeof(BookStoreApplicationContractsModule),
    typeof(AbpIdentityApplicationModule),
    typeof(AbpPermissionManagementApplicationModule),
    typeof(AbpTenantManagementApplicationModule),
    typeof(AbpFeatureManagementApplicationModule),
    typeof(AbpSettingManagementApplicationModule)
    )]
public class BookStoreApplicationModule : AbpModule
{
    public override void ConfigureServices(ServiceConfigurationContext context)
    {
        Configure<AbpAutoMapperOptions>(options =>
        {
            options.AddMaps<BookStoreApplicationModule>();
        });

        // 注册拦截器
        context.Services.AddMvcCore(x=> x.Filters.Add<AopInterceptor>());

    }
}


http://www.kler.cn/a/540674.html

相关文章:

  • Docker容器访问外网:启动时的网络参数配置指南
  • 综合评价 | 基于随机变异系数-TOPSIS组合法的综合评价模型(Matlab)
  • C++基础系列【8】如何解决编译器报的错误
  • 常见的前端框架和库有哪些
  • 音频进阶学习十一——离散傅里叶级数DFS
  • 人工智能浪潮下脑力劳动的变革与重塑:挑战、机遇与应对策略
  • 如何使用Socket编程在Python中实现实时聊天应用
  • 笔试-字符串2
  • Web前端开发--HTML
  • java后端开发day10--综合练习(一)
  • 基于“感知–规划–行动”的闭环系统架构
  • DeepSeek+3D视觉机器人应用场景、前景和简单设计思路
  • 深入理解TCP/IP协议栈:从原理到实践
  • Linux: ASoC 声卡硬件参数的设置过程简析
  • 协议-ACLLite-ffmpeg
  • C++ STL算法总结
  • salesforce 中 Account 转移给新 Owner 后如何仅转移 Case,而不转移 Opportunity
  • 怎么编写AI模型prompt(提问,表达需求)
  • ZooKeeper Watcher 机制详解:从注册到回调的全过程
  • Vue07
  • vi 是 Unix 和 Linux 系统中常用的文本编辑器
  • 易仓与金蝶云星空无缝集成:实现高效R调拨入库
  • 如何在浏览器中搭建开源Web操作系统Puter的本地与远程环境
  • Python 高阶函数(详解)
  • 主机安全:数字时代的基石
  • harmonyOS的路由跳转及数据请求