net core Webapi基础工程搭建(七)——小试AOP及常规测试_Part 2

前言

前一篇讲到了中间层的使用,可能不是那么AOP,今天主要来讲下一个轻量级的AOP第三方类库AspectoCorejson

简单介绍下这个类库,AspectCore Project 是适用于 net core 平台的轻量级 Aop(Aspect-oriented programming) 解决方案,它更好的遵循 net core 的模块化开发理念,使用AspectCore能够更容易构建低耦合、易扩展的Web应用程序。api

引入

首先,咱们在Util层直接引入相关的类库。app

引入
而后咱们仍是先在Startup注册下,将ConfigureServices方法从void更改成IServiceProvider,目的就是,这个管道给别人了,再也不由默认的来了。async

public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        //...以前的
        services.AddAspectCoreContainer();
        return services.BuildAspectInjectorProvider();
    }

自定义属性

写完以后,咱们就能够来试试这个玩意儿怎么玩了,很少说,Util来个文件夹Attributes,而后新建一个类AprilLogAttribute,继承AbstractInterceptorAttributeide

public class AprilLogAttribute : AbstractInterceptorAttribute
    {
        public async override Task Invoke(AspectContext context, AspectDelegate next)
        {
            LogUtil.Debug("AprilLogAttribute begin");
            await next(context);
            LogUtil.Debug("AprilLogAttribute end");
        }
    }

没啥具体的使用注解,就是加个先后注释的做用。而后咱们在以前的Student这个接口中加上一个测试方法。模块化

public interface IStudentService : IBaseService<StudentEntity>
    {
        [AprilLog]
        void Test();
    }

StudentService咱们来实现这个方法。测试

public class StudentService : BaseService<StudentEntity>, IStudentService
    {
        public void Test()
        {
            LogUtil.Debug("StudentService Test");
        }
    }

测试

所有搞定以后,咱们继续Values开刀,注释掉以前的代码以后,只留一个Test方法。优化

[HttpGet]
        public ActionResult<IEnumerable<string>> Get()
        {
            _service.Test();
            return new string[] { "value1", "value2" };
        }

别忘了运行前在application.json里面加上接口白名单。ui

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "CommonSettings": {
    "FilePath": "/uploads/files/"
  },
  "DefaultSqlConnectionString": {
    "MySql": "server=127.0.0.1;userid=root;password=root;database=test;"
  },
  "AllowUrl": "/api/Values" //这个若是没有那一直是返回未登陆
}

测试
运行没问题,咱们来看下日志记录。
日志
另外也补充下这个记录的问题,若是须要监视接口调用的状况,咱们能够加上断点看下这个context,这个对象里面自己已经包含了咱们调用了哪一个接口的哪一个方法等等信息,这里只举个简单的例子,咱们能够知道咱们调用的接口及方法,包括实现及方法,而后能够记录下是谁访问,哪一个接口,执行时间等等。

示例

小结

写到这里,net core webapi的基础工程基本上已经完工了,经过这些记录我自己又对以前的工程进行了小量的改动,每次的一版写完都有一个新的感觉,可能当时写一版的时候没有想太多,一遍一遍的过完以后发现有些地方能够优化,而且优化的效果也是挺明显,后续若是有新的功能实现或者业务须要的时候,也会同步更新的这个示例工程。

相关文章
相关标签/搜索