.Net6自定义拦截器

发布时间 2023-05-23 10:01:47作者: 白码一号

.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 然后进入自定义拦截器再进入特性的构造函数获取值

打印结果如下