大橙子网站建设,新征程启航
为企业提供网站建设、域名注册、服务器等服务
本篇内容主要讲解“如何使用ActionFilterAttribute实现API日志的记录”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“如何使用ActionFilterAttribute实现API日志的记录”吧!
公司主营业务:做网站、网站建设、移动网站开发等业务。帮助企业客户真正实现互联网宣传,提高企业的竞争能力。创新互联建站是一支青春激扬、勤奋敬业、活力青春激扬、勤奋敬业、活力澎湃、和谐高效的团队。公司秉承以“开放、自由、严谨、自律”为核心的企业文化,感谢他们对我们的高要求,感谢他们从不同领域给我们带来的挑战,让我们激情的团队有机会用头脑与智慧不断的给客户带来惊喜。创新互联建站推出永仁免费做网站回馈大家。
实现方式
1、首先在进入action的时候,定义OnActionExecuting。
public override void OnActionExecuting(ActionExecutingContext context) { base.OnActionExecuting(context); // 后续添加了获取请求的请求体,如果在实际项目中不需要删除即可 long contentLen = context.HttpContext.Request.ContentLength == null ? 0 : context.HttpContext.Request.ContentLength.Value; if (contentLen > 0) { // 读取请求体中所有内容 System.IO.Stream stream = context.HttpContext.Request.Body; if (context.HttpContext.Request.Method == "POST") { stream.Position = 0; } byte[] buffer = new byte[contentLen]; stream.Read(buffer, 0, buffer.Length); // 转化为字符串 RequestBody = System.Text.Encoding.UTF8.GetString(buffer); } ActionArguments = Newtonsoft.Json.JsonConvert.SerializeObject(context.ActionArguments); Stopwatch = new Stopwatch(); Stopwatch.Start(); }
2、定义Stopwatch ,计算方法的耗时。
private string ActionArguments { get; set; } ////// 请求体中的所有值 /// private string RequestBody { get; set; } private Stopwatch Stopwatch { get; set; }
3、结束的时候,把信息打印出来OnActionExecuted。
public override void OnActionExecuted(ActionExecutedContext context) { base.OnActionExecuted(context); Stopwatch.Stop(); string url = context.HttpContext.Request.Host + context.HttpContext.Request.Path + context.HttpContext.Request.QueryString; string method = context.HttpContext.Request.Method; string controller = context.Controller.ToString(); string action = context.ActionDescriptor.DisplayName; string token = ""; if (context.HttpContext.Request != null && context.HttpContext.Request.Headers != null && context.HttpContext.Request.Headers["Authorization"].Count > 0) { token = context.HttpContext.Request.Headers["Authorization"]; } string qs = ActionArguments; dynamic result = context?.Result?.GetType()?.Name == "EmptyResult" ? new { Value = "无返回结果" } : context?.Result as dynamic; string res = "在返回结果前发生了异常"; try { if (result != null) { res = Newtonsoft.Json.JsonConvert.SerializeObject(result.Value); } } catch (System.Exception) { res = "日志未获取到结果,返回的数据无法序列化"; } NLogger.Info( $"地址:{url} \n " + $"controller:{controller} \n " + $"action:{action} \n " + $"token:{token} \n " + $"方式:{method} \n " + $"请求体:{RequestBody} \n " + $"参数:{qs}\n " + $"结果:{res}\n " + $"耗时:{Stopwatch.Elapsed.TotalMilliseconds} 毫秒(指控制器内对应方法执行完毕的时间)"); }
4、控制器调用LogAttribute。
////// /// [Produces("application/json")] [LogAttribute] [CustomExceptionFilterAttribute] public class DefaultController : Controller { }
完整代码
using CompanyName.ProjectName.Core; using Microsoft.AspNetCore.Mvc.Filters; using System.Diagnostics; namespace CompanyName.ProjectName.HttpApi.Host.Code { ////// 拦截器 /// public class LogAttribute : ActionFilterAttribute { private string ActionArguments { get; set; } ////// 请求体中的所有值 /// private string RequestBody { get; set; } private Stopwatch Stopwatch { get; set; } ////// /// /// public override void OnActionExecuting(ActionExecutingContext context) { base.OnActionExecuting(context); // 后续添加了获取请求的请求体,如果在实际项目中不需要删除即可 long contentLen = context.HttpContext.Request.ContentLength == null ? 0 : context.HttpContext.Request.ContentLength.Value; if (contentLen > 0) { // 读取请求体中所有内容 System.IO.Stream stream = context.HttpContext.Request.Body; if (context.HttpContext.Request.Method == "POST") { stream.Position = 0; } byte[] buffer = new byte[contentLen]; stream.Read(buffer, 0, buffer.Length); // 转化为字符串 RequestBody = System.Text.Encoding.UTF8.GetString(buffer); } ActionArguments = Newtonsoft.Json.JsonConvert.SerializeObject(context.ActionArguments); Stopwatch = new Stopwatch(); Stopwatch.Start(); } ////// /// /// public override void OnActionExecuted(ActionExecutedContext context) { base.OnActionExecuted(context); Stopwatch.Stop(); string url = context.HttpContext.Request.Host + context.HttpContext.Request.Path + context.HttpContext.Request.QueryString; string method = context.HttpContext.Request.Method; string controller = context.Controller.ToString(); string action = context.ActionDescriptor.DisplayName; string token = ""; if (context.HttpContext.Request != null && context.HttpContext.Request.Headers != null && context.HttpContext.Request.Headers["Authorization"].Count > 0) { token = context.HttpContext.Request.Headers["Authorization"]; } string qs = ActionArguments; dynamic result = context?.Result?.GetType()?.Name == "EmptyResult" ? new { Value = "无返回结果" } : context?.Result as dynamic; string res = "在返回结果前发生了异常"; try { if (result != null) { res = Newtonsoft.Json.JsonConvert.SerializeObject(result.Value); } } catch (System.Exception) { res = "日志未获取到结果,返回的数据无法序列化"; } NLogger.Info( $"地址:{url} \n " + $"controller:{controller} \n " + $"action:{action} \n " + $"token:{token} \n " + $"方式:{method} \n " + $"请求体:{RequestBody} \n " + $"参数:{qs}\n " + $"结果:{res}\n " + $"耗时:{Stopwatch.Elapsed.TotalMilliseconds} 毫秒(指控制器内对应方法执行完毕的时间)"); } } }
到此,相信大家对“如何使用ActionFilterAttribute实现API日志的记录”有了更深的了解,不妨来实际操作一番吧!这里是创新互联网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!