posts - 52,comments - 30,views - 13万

.Net6自定义拦截器

拦截器是Aop(面向切面编程)的思想指的是不改变原代码封装的前提下去实现更多功能

这里通过.net的特性(给一个目标对象添加一段配置信息)的方式去实现拦截器功能

新建一个特性

复制代码
namespace CorePolly
{
    public class TestAttribute: Attribute
    {
        public string Name { get; set; }

        public string Value { get; set; }

        public string Data { get; set; }

        public TestAttribute(string name,string value, string data)
        {
            Name = name;
            Value = value;
            Data = data;
        }

    }
}
复制代码

 再新建一个自定义拦截器的类 继承 IInterceptor 并实现 Interceptor 方法

复制代码
using Castle.DynamicProxy;
using System.Reflection;

namespace CorePolly
{
    [AttributeUsage(AttributeTargets.Method)]
    public class TestPolicyInterceptor : Attribute, IInterceptor
    {
        public void Intercept(IInvocation invocation)
        {
            TestAttribute pollyPolicyConfigAttribute = invocation.Method.GetCustomAttribute<TestAttribute>()!;
            Console.WriteLine($@"我是自定义拦截器名称是:{pollyPolicyConfigAttribute.Name}");
        }
    }
}
复制代码

然后定义一个IService 和 Service 提供相应的服务

复制代码
using Autofac.Extras.DynamicProxy;
using Microsoft.AspNetCore.Routing;

namespace CorePolly.IService
{
    [Intercept(typeof(TestPolicyInterceptor))]
    public interface IUserService
    {
        [TestAttribute("我是自定义拦截器","value","data")]
        User AOPGetById(int id);

        [TestAttribute("我是自定义拦截器", "value", "data")]
        public string GetById(int id);
    }

    public record User(int Id, string Name, string Account, string Password);
}
复制代码
复制代码
using CorePolly.IService;

namespace CorePolly.Service
{
    public class UserServiceBy: IUserService
    {
        public string AOPGetById(int id)
        {return id.ToString();
        }

        public string GetById(int id)
        {
            return id.ToString();
        }
    }
}
复制代码

然后在controllers中调用

复制代码
using CorePolly.IService;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Polly;
using System.Net;

namespace CorePolly.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class HomeController : ControllerBase
    {
        private readonly IUserService _userService;
        public HomeController(IUserService userService)
        {
            _userService = userService;
        }

        public IActionResult GetFunction()
        {
            _userService.AOPGetById(11);
Console.WriteLine("123");
return Ok("123"); } public IActionResult Get() {
       Console.WriteLine("123");
return new ObjectResult("111") { StatusCode = 500, Value = "Home" }; }
}

   }    

复制代码

最后再porgram中依赖注入一下

复制代码
using CorePolly;
using CorePolly.IService;
using CorePolly.Service;
using Autofac;
using System.Reflection;
using Autofac.Extensions.DependencyInjection;
using Autofac.Extras.DynamicProxy;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();// 以下是autofac依赖注入
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
builder.Host.ConfigureContainer<ContainerBuilder>(builder =>
{
    //先注入JWT
    //builder.RegisterType<AuthorizeJWT>().As<IAuthorizeJWT>();//可以是其他接口和类                                                      // 注入Service程序集
    //Assembly assembly = Assembly.Load(ServiceAutofac.GetAssemblyName());//可以是其他程序集
    //builder.RegisterAssemblyTypes(assembly)
    //.AsImplementedInterfaces()
    //.InstancePerDependency();

    builder.RegisterType<UserServiceBy>().As<IUserService>().SingleInstance().EnableInterfaceInterceptors();
    builder.RegisterType<CustomPollyPolicyInterceptor>();
    builder.RegisterType<TestPolicyInterceptor>();
});


var app = builder.Build();

// Configure the HTTP request pipeline.

app.UseAuthorization();

app.MapControllers();

app.Run();
复制代码

程序启动后先进入controllers 然后进入自定义拦截器再进入特性的构造函数获取值

打印结果如下

 下面是.netCore基于 ActionFilterAttribute 过滤器实现所有入参自动打印,响应值自动记录

复制代码
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;

namespace CorePolly.Filter
{
    public class HelloFilter : ActionFilterAttribute
    {
        /// <summary>
        /// 方法执行之前执行
        /// </summary>
        /// <param name="context"></param>
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            Console.WriteLine("方法执行之前执行");

            var descriptor = context.ActionDescriptor as ControllerActionDescriptor;
            string param = string.Empty;
            string globalParam = string.Empty;

            foreach (var arg in context.ActionArguments)
            {
                string value = Newtonsoft.Json.JsonConvert.SerializeObject(arg.Value);
                param += $"{arg.Key} : {value} \r\n";
                globalParam += value;
            }
            Console.WriteLine($"webapi方法名称:【{descriptor.ActionName}】接收到参数为:{param} 方法请求的方式{context.HttpContext.Request.Method}");

            //base.OnActionExecuting(context);
        }

        /// <summary>
        /// 方法调用之后执行
        /// </summary>
        /// <param name="context"></param>
        public override void OnActionExecuted(ActionExecutedContext context)
        {
            Console.WriteLine("方法调用之后执行");
            //base.OnActionExecuted(context);
        }

        /// <summary>
        /// result方法调用前执行
        /// </summary>
        /// <param name="context"></param>
        public override void OnResultExecuting(ResultExecutingContext context)
        {
            Console.WriteLine("result方法调用前执行");
            //base.OnResultExecuting(context);
        }

        /// <summary>
        /// result 方法调用后执行
        /// </summary>
        /// <param name="context"></param>
        public override void OnResultExecuted(ResultExecutedContext context)
        {
            Console.WriteLine("result 方法调用后执行");

            var descriptor = context.ActionDescriptor as ControllerActionDescriptor;

            string result = string.Empty;
            if (context.Result is ObjectResult)
            {
                result = Newtonsoft.Json.JsonConvert.SerializeObject(((ObjectResult)context.Result).Value);
            }

            Console.WriteLine($"webapi方法名称【{descriptor.ActionName}】执行的返回值 :  {result}");
            //base.OnResultExecuted(context);
        }
    }
}
复制代码

然后在控制器上进行标记即可

 

posted on   白码一号  阅读(628)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
< 2025年3月 >
23 24 25 26 27 28 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 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示