使用ActionFilter添加日志
过滤器分类:
Core WebApi:的几种过滤器:
1.授权过滤器:AuthorizeAttribute.
2.异常过滤器:IExceptionFilter , IAsyncExceptionFilter
3.方法过滤器: ActionfilterAttribute, IActionFilter , IAsyncActionFilter.
后边两种是相对asp.net framwork来讲,asp.net core所特有的
4.资源过滤器:IResourceFilter
5.结果过滤器:ResultFilterAttribute, IResultFilter, IAsyncResultFilter
本文使用第三种IActionFileter来实现日志记录,具体步骤如下:
1.新建一个CustiomActionFilterAttribute的类
public class CustiomActionFilterAttribute : Attribute, IActionFilter//也可以直接继承ActionFilter
{
public void OnActionExecuted(ActionExecutedContext context)
{
Console.WriteLine("this is CustiomActionFilterAttribute.OnActionExecuted");
}
public void OnActionExecuting(ActionExecutingContext context)
{
Console.WriteLine("this is CustiomActionFilterAttribute.OnActionExecuting");
}
}
2.将此特性添加到要调用的Action方法上(当然也可放在类上,实现全局调用)
//上边还有该类的构造函数,为精简篇幅此处省略
[Route("GetInfoByParamter")]
[HttpGet]
[CustiomActionFilter]//以特性的方式标记,只能支持无参数的构造函数:
public string GetInByParamter(int id, string Name)
{
Console.WriteLine($"this is {id }的{Name}");
return $"this is {id }的{Name}";
}
3.运行调用后,观察控制台结果
由上边结果可以看出来:ActionFilterAttribute方法,是先调用构造函数,然后再进入类的实例里面,所以依靠他的这种特性,我们可以实现日志记录的功能;
4.在CustiomActionFilterAttribute类里面添加与日志相关的代码:
其中context是个功能很强大的函数,注意如何通过他来调用运行时的相关信息。其中context.RouteData.values[’‘action’’]定位到的是调用的api方法
public class CustiomActionFilterAttribute : ActionFilterAttribute
{
private readonly ILogger<CustiomActionFilterAttribute> logger;
public CustiomActionFilterAttribute(ILogger<CustiomActionFilterAttribute> logger)
{
this.logger = logger;
}
public void OnActionExecuted(ActionExecutedContext context)
{
var strLog = $"{DateTime.Now}执行后{context.RouteData.Values["action"]}api," +
$" 参数是{context.Result}"; //如何查调用的API
logger.LogInformation(strLog);
Console.WriteLine("this is CustiomActionFilterAttribute.OnActionExecuted");
}
public void OnActionExecuting(ActionExecutingContext context)
{
var strLog = $"{DateTime.Now}开始调用的{context.RouteData.Values["action"]}api," +
$" 参数是{context.ActionArguments}"; //如何查调用的API
logger.LogInformation(strLog);
Console.WriteLine("this is CustiomActionFilterAttribute.OnActionExecuting");
}
}
5.如何调用? 在Action方法上添加ActionFilter特性
此次调用,不再是直接添加 [CustiomActionFilter] 而是使用 [TypeFilter(typeof(CustiomActionFilterAttribute))] 因为直接添加特性,只能应用于无参函数时;
[Route("GetInfoByParamter")]
[HttpGet]
// [CustiomActionFilter]//以特性的方式标记,只能支持无参数的构造函数:
[TypeFilter(typeof(CustiomActionFilterAttribute))]
public string GetInByParamter(int id, string Name)
{
Console.WriteLine($"this is {id }的{Name}");
return $"this is {id }的{Name}";
}
可查看运行后的结果(控制台的输出)
此时已经实现了ActionFilter的基本调用,如果要实现更复杂的功能,可以自定义Filter;
题外话:如何用swagger完成测试