AspectCore 配合 Log4Net 全局记录Asp.Net Core Web Api异常日志

配置AspectCore-Framework 首先通过Nuget安装AspectCore.Extensions.DependencyInjection。 接下来我们可以配置拦截器: //继承自AbstractInterceptorAttribute public class CustomInterceptorAttribute : AbstractInterceptorAttribute { public override async Task Invoke(AspectContext context, AspectDelegate next) { try { Console.WriteLine("调用前"); await next(context);//执行调用的方法等 } catch (Exception ex) { Console.WriteLine("捕获到异常"); throw; } finally { Console.WriteLine("调用结束"); } } } 然后在Startup.cs中的ConfigureServices方法中配置代理(.NET6中对应的是builder.Services) services.ConfigureDynamicProxy(config => { services.AddTransient<IExmapleService, ExmapleService>(); services.AddControllers(); config.Interceptors.AddTyped<CustomInterceptorAttribute>(Predicates.ForService("*Service")); config.Interceptors.AddTyped<CustomInterceptorAttribute>(Predicates.ForService("*Controller")); }); 以上配置是对名称以Service或Controller结尾的进行代理,还有其他一些规则如: //全部代理 config.Interceptors.AddTyped<CustomInterceptorAttribute>(); //名称以Execute开头的方法会被代理 config.Interceptors.AddTyped<CustomInterceptorAttribute>(Predicates.ForMethod("Execute*")); //以Service结尾则不会被代理 config.NonAspectPredicates.AddService("Service"); //更多详细规则可以查阅官方文档 //https://github.com/dotnetcore/AspectCore-Framework/blob/master/docs/1.%E4%BD%BF%E7%94%A8%E6%8C%87%E5%8D%97.md ...... 也可以通过NonAspectAttribute对Service或Method进行单独设置: //无论在Startup.cs中如何配置,该接口都不会通过代理 [NonAspect] public interface IExampleService { void Method(); } 最后在Program....

February 27, 2021 · 2 分钟 · Remo