GlobalExceptionMiddleware.cs 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. using Infrastructure;
  2. using Infrastructure.Attribute;
  3. using Infrastructure.Model;
  4. using IPTools.Core;
  5. using Microsoft.AspNetCore.Http;
  6. using Microsoft.AspNetCore.Http.Features;
  7. using NLog;
  8. using System;
  9. using System.Text.Encodings.Web;
  10. using System.Text.Json;
  11. using System.Threading.Tasks;
  12. using ZR.Admin.WebApi.Extensions;
  13. using ZR.Common;
  14. using ZR.Model.System;
  15. using ZR.Service.System.IService;
  16. namespace ZR.Admin.WebApi.Middleware
  17. {
  18. /// <summary>
  19. /// 全局异常处理中间件
  20. /// 调用 app.UseMiddleware<GlobalExceptionMiddleware>();
  21. /// </summary>
  22. public class GlobalExceptionMiddleware
  23. {
  24. private readonly RequestDelegate next;
  25. private readonly ISysOperLogService SysOperLogService;
  26. static readonly Logger Logger = LogManager.GetCurrentClassLogger();//声明NLog变量
  27. public GlobalExceptionMiddleware(RequestDelegate next, ISysOperLogService sysOperLog)
  28. {
  29. this.next = next;
  30. this.SysOperLogService = sysOperLog;
  31. }
  32. public async Task Invoke(HttpContext context)
  33. {
  34. try
  35. {
  36. await next(context);
  37. }
  38. catch (Exception ex)
  39. {
  40. await HandleExceptionAsync(context, ex);
  41. }
  42. }
  43. private async Task HandleExceptionAsync(HttpContext context, Exception ex)
  44. {
  45. NLog.LogLevel logLevel = NLog.LogLevel.Info;
  46. int code = (int)ResultCode.GLOBAL_ERROR;
  47. string msg;
  48. string error = string.Empty;
  49. //自定义异常
  50. if (ex is CustomException customException)
  51. {
  52. code = customException.Code;
  53. msg = customException.Message;
  54. error = customException.LogMsg;
  55. }
  56. else if (ex is ArgumentException)//参数异常
  57. {
  58. code = (int)ResultCode.PARAM_ERROR;
  59. msg = ex.Message;
  60. }
  61. else
  62. {
  63. msg = "服务器好像出了点问题......";
  64. error = $"{ex.Message}";
  65. logLevel = NLog.LogLevel.Error;
  66. context.Response.StatusCode = 500;
  67. }
  68. var options = new JsonSerializerOptions
  69. {
  70. Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
  71. PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
  72. WriteIndented = true
  73. };
  74. ApiResult apiResult = new(code, msg);
  75. string responseResult = JsonSerializer.Serialize(apiResult, options).ToLower();
  76. string ip = HttpContextExtension.GetClientUserIp(context);
  77. var ip_info = IpTool.Search(ip);
  78. SysOperLog sysOperLog = new()
  79. {
  80. Status = 1,
  81. OperIp = ip,
  82. OperUrl = HttpContextExtension.GetRequestUrl(context),
  83. RequestMethod = context.Request.Method,
  84. JsonResult = responseResult,
  85. ErrorMsg = string.IsNullOrEmpty(error) ? msg : error,
  86. OperName = context.User.Identity.Name,
  87. OperLocation = ip_info.Province + " " + ip_info.City,
  88. OperTime = DateTime.Now
  89. };
  90. HttpContextExtension.GetRequestValue(context, sysOperLog);
  91. var endpoint = GetEndpoint(context);
  92. if (endpoint != null)
  93. {
  94. var logAttribute = endpoint.Metadata.GetMetadata<LogAttribute>();
  95. if (logAttribute != null)
  96. {
  97. sysOperLog.BusinessType = (int)logAttribute?.BusinessType;
  98. sysOperLog.Title = logAttribute?.Title;
  99. sysOperLog.OperParam = logAttribute.IsSaveRequestData ? sysOperLog.OperParam : "";
  100. sysOperLog.JsonResult = logAttribute.IsSaveResponseData ? sysOperLog.JsonResult : "";
  101. }
  102. }
  103. LogEventInfo ei = new(logLevel, "GlobalExceptionMiddleware", error)
  104. {
  105. Exception = ex,
  106. Message = error
  107. };
  108. ei.Properties["status"] = 1;//走正常返回都是通过走GlobalExceptionFilter不通过
  109. ei.Properties["jsonResult"] = responseResult;
  110. ei.Properties["requestParam"] = sysOperLog.OperParam;
  111. ei.Properties["user"] = HttpContextExtension.GetName(context);
  112. Logger.Log(ei);
  113. context.Response.ContentType = "text/json;charset=utf-8";
  114. await context.Response.WriteAsync(responseResult, System.Text.Encoding.UTF8);
  115. WxNoticeHelper.SendMsg("系统出错", sysOperLog.ErrorMsg);
  116. SysOperLogService.InsertOperlog(sysOperLog);
  117. }
  118. public static Endpoint GetEndpoint(HttpContext context)
  119. {
  120. if (context == null)
  121. {
  122. throw new ArgumentNullException(nameof(context));
  123. }
  124. return context.Features.Get<IEndpointFeature>()?.Endpoint;
  125. }
  126. }
  127. }