首页 > 其他分享 >.Net6自定义拦截器

.Net6自定义拦截器

时间:2023-05-23 10:00:30浏览次数:38  
标签:拦截器 string 自定义 builder CorePolly using Net6 public

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

打印结果如下

 

标签:拦截器,string,自定义,builder,CorePolly,using,Net6,public
From: https://www.cnblogs.com/OneSeting/p/17422390.html

相关文章

  • goframe API 自定义接口返回值处理
    前言goframe默认使用了中间键ghttp.MiddlewareHandlerResponse,HTTPServer的数据返回通过ghttp.Response对象实现,ghttp.Response对象实现了标准库的http.ResponseWriter接口。数据输出使用Write*相关方法实现,并且数据输出采用了Buffer机制,因此数据的处理效率比较高......
  • 一个基础的vue图片放大镜自定义指令
    <template> <div>  <divv-magnifyref="content"class="content">   <imgsrc="https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg"alt="">  </div> </d......
  • 记Perfeye自定义项实现对比需求
    记Perfeye自定义项实现对比需求背景Perfyeye平台很早就支持对比功能了,但是支持的模块不全,需求方现在想要支持自定义列的需求对比功能,用来显示多份报告之间的差异以及性能趋势。刚接到这个需求的时候,我想,这不就是简简单单CV复制一下老代码的逻辑,改改相应字段就可以了,30分钟也......
  • 在Windows Server 2022中使用Microsoft Deployment Toolkit(MDT)时,可使用Rules(规则)文件
    在WindowsServer2022中使用MicrosoftDeploymentToolkit(MDT)时,可使用Rules(规则)文件来配置和自定义部署过程。以下是常见的Rules参数及其描述:UserDomain:指定要加入的域的名称。UserID和UserPassword:指定加入域所需的管理员帐户凭据。TimeZoneName:指定安装期间使用的时区。Jo......
  • 【Git学习】git log自定义格式
    定制自己常用格式:1、二进制作者时间提交备注gitlog–pretty=format:”%h-%an,%ar:%s”2、以图表形式查看远程提交记录gitlog–decorate–oneline–graph3、说明:常用的格式占位符写法及其代表的意义。选项说明%H提交对象(commit)的完整哈希字串%h提交对象的简短......
  • 基于 Socket 接口实现自定义协议通信
    访问【WRITE-BUG数字空间】_[内附完整源码和文档]根据自定义的协议规范,使用Socket编程接口编写基本的网络应用软件。掌握C语言形式的Socket编程接口用法,能够正确发送和接收网络数据包开发一个客户端,实现人机交互界面和与服务器的通信开发一个服务端,实现并发处理多个客户端......
  • flutter dio自定义http client
    finaldio=Dio();DiogetMyDio(){initAdapter();dio.options.headers={'apiKey':'xxxxx'};dio.options.connectTimeout=constDuration(seconds:15);dio.options.receiveTimeout=constDuration(seconds:15);di......
  • springboot自定义拦截器
    之前使用过滤器实现了拦截没有登录的请求,现在使用springboot的拦截器实现1.LoginCheckInterceptor.javapackagecom.minqiliang.interceptor;importcom.alibaba.fastjson.JSONObject;importcom.minqiliang.pojo.Result;importcom.minqiliang.utils.JwtUtils;importlomb......
  • SpringBoot利用自定义注解实现多数据源
    自定义多数据源SpringBoot利用自定义注解实现多数据源,前置知识:注解、Aop、SpringBoot整合Mybaits1、搭建工程创建一个SpringBoot工程,并引入依赖<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring......
  • Wordpress自定义小工具(Widget)简单案例
    在主题对应目录创建文件如widgets.php<?php//继承了WP_Widget这个类来创建新的小工具(Widget):可在后台外观-小工具中添加此自定义小工具到页面具体位置classmy_widgetextendsWP_Widget{publicfunction__construct() { //$widget_ops可以给小工具进......