1. public class LogAttribute : ActionFilterAttribute {
  2. private string LogFlag { get; set; }
  3. private string ActionArguments { get; set; }
  4. /// <summary>
  5. /// 请求体中的全部值
  6. /// </summary>
  7. private string RequestBody { get; set; }
  8. private Stopwatch Stopwatch { get; set; }
  9. public LogAttribute(string logFlag) {
  10. LogFlag = logFlag;
  11. }
  12. public override void OnActionExecuting(ActionExecutingContext context) {
  13. base.OnActionExecuting(context);
  14. // 后续添加了获取请求的请求体,若是在实际项目中不须要删除便可
  15. long contentLen = context.HttpContext.Request.ContentLength == null ? 0 : context.HttpContext.Request.ContentLength.Value;
  16. if (contentLen > 0) {
  17. // 读取请求体中全部内容
  18. System.IO.Stream stream = context.HttpContext.Request.Body;
  19. if (context.HttpContext.Request.Method == "POST") {
  20. stream.Position = 0;
  21. }
  22. byte[] buffer = new byte[contentLen];
  23. stream.Read(buffer, 0, buffer.Length);
  24. // 转化为字符串
  25. RequestBody = System.Text.Encoding.UTF8.GetString(buffer);
  26. }
  27. ActionArguments = Newtonsoft.Json.JsonConvert.SerializeObject(context.ActionArguments);
  28. Stopwatch = new Stopwatch();
  29. Stopwatch.Start();
  30. }
  31. public override void OnActionExecuted(ActionExecutedContext context) {
  32. base.OnActionExecuted(context);
  33. Stopwatch.Stop();
  34. string url = context.HttpContext.Request.Host + context.HttpContext.Request.Path + context.HttpContext.Request.QueryString;
  35. string method = context.HttpContext.Request.Method;
  36. string qs = ActionArguments;
  37. dynamic result = context.Result.GetType().Name == "EmptyResult" ? new { Value = "无返回结果" } : context.Result as dynamic;
  38. string res = "在返回结果前发生了异常";
  39. try {
  40. if (result != null) {
  41. res = Newtonsoft.Json.JsonConvert.SerializeObject(result.Value);
  42. }
  43. } catch (System.Exception) {
  44. res = "日志未获取到结果,返回的数据没法序列化";
  45. }
  46. LogException.AddLog($"\n 方法:{LogFlag} \n " +
  47. $"地址:{url} \n " +
  48. $"方式:{method} \n " +
  49. $"请求体:{RequestBody} \n " +
  50. $"参数:{qs}\n " +
  51. $"结果:{res}\n " +
  52. $"耗时:{Stopwatch.Elapsed.TotalMilliseconds} 毫秒(指控制器内对应方法执行完毕的时间)");
  53. }
  54. }

使用方式

image.png

运行结果

image.png