GlobalExceptionMiddleware.cs 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. using Attribute;
  2. using Extensions;
  3. using Infrastructure;
  4. using Infrastructure.Model;
  5. using IPTools.Core;
  6. using Microsoft.AspNetCore.Http.Features;
  7. using Model;
  8. using NLog;
  9. using Services;
  10. using System.Text.Encodings.Web;
  11. using textJson = System.Text.Json;
  12. namespace Middleware
  13. {
  14. /// <summary>
  15. /// 全局异常处理中间件
  16. /// 调用 app.UseMiddlewareGlobalExceptionMiddleware>();
  17. /// </summary>
  18. public class GlobalExceptionMiddleware
  19. {
  20. private readonly RequestDelegate next;
  21. // private readonly ISysOperLogService SysOperLogService;
  22. static readonly Logger Logger = LogManager.GetCurrentClassLogger();
  23. public GlobalExceptionMiddleware(RequestDelegate next)
  24. {
  25. this.next = next;
  26. // this.SysOperLogService = sysOperLog;
  27. }
  28. public async Task Invoke(HttpContext context)
  29. {
  30. try
  31. {
  32. // 设置允许跨域的域名、方法等
  33. context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
  34. context.Response.Headers.Add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
  35. context.Response.Headers.Add("Access-Control-Allow-Headers", "DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization");
  36. // 如果请求方法是预检请求(OPTIONS),则直接返回成功状态码
  37. if (context.Request.Method == "OPTIONS")
  38. {
  39. context.Response.StatusCode = 200;
  40. await context.Response.WriteAsync("OK");
  41. return;
  42. }
  43. await next(context);
  44. }
  45. catch (Exception ex)
  46. {
  47. await HandleExceptionAsync(context, ex);
  48. }
  49. }
  50. private async Task HandleExceptionAsync(HttpContext context, Exception ex)
  51. {
  52. NLog.LogLevel logLevel = NLog.LogLevel.Info;
  53. int code = (int)ResultCode.GLOBAL_ERROR;
  54. string msg;
  55. string error = string.Empty;
  56. bool notice = true;
  57. //自定义异常
  58. if (ex is CustomException customException)
  59. {
  60. code = customException.Code;
  61. msg = customException.Message;
  62. error = customException.LogMsg;
  63. notice = customException.Notice;
  64. }
  65. else if (ex is ArgumentException)//参数异常
  66. {
  67. code = (int)ResultCode.PARAM_ERROR;
  68. msg = ex.Message;
  69. }
  70. else
  71. {
  72. msg = "服务器好像出了点问题,请联系系统管理员...";
  73. error = $"{ex.Message}";
  74. logLevel = NLog.LogLevel.Error;
  75. context.Response.StatusCode = 500;
  76. }
  77. var options = new textJson.JsonSerializerOptions
  78. {
  79. Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
  80. PropertyNamingPolicy = textJson.JsonNamingPolicy.CamelCase,
  81. WriteIndented = true
  82. };
  83. ApiResult apiResult = new(code, msg);
  84. string responseResult = textJson.JsonSerializer.Serialize(apiResult, options);
  85. // string ip = HttpContextExtension.GetClientUserIp(context);
  86. // var ip_info = IpTool.Search(ip);
  87. // SysOperLog sysOperLog = new()
  88. // {
  89. // Status = 1,
  90. // // OperIp = ip,
  91. // OperUrl = HttpContextExtension.GetRequestUrl(context),
  92. // RequestMethod = context.Request.Method,
  93. // JsonResult = responseResult,
  94. // ErrorMsg = string.IsNullOrEmpty(error) ? msg : error,
  95. // OperName = HttpContextExtension.GetName(context),
  96. // // OperLocation = ip_info.Province + " " + ip_info.City,
  97. // OperTime = DateTime.Now,
  98. // OperParam = HttpContextExtension.GetRequestValue(context, context.Request.Method)
  99. // };
  100. var endpoint = GetEndpoint(context);
  101. if (endpoint != null)
  102. {
  103. var logAttribute = endpoint.Metadata.GetMetadata<LogAttribute>();
  104. if (logAttribute != null)
  105. {
  106. // sysOperLog.BusinessType = (int)logAttribute.BusinessType;
  107. // sysOperLog.Title = logAttribute?.Title;
  108. // sysOperLog.OperParam = logAttribute.IsSaveRequestData ? sysOperLog.OperParam : "";
  109. // sysOperLog.JsonResult = logAttribute.IsSaveResponseData ? sysOperLog.JsonResult : "";
  110. }
  111. }
  112. LogEventInfo ei = new(logLevel, "GlobalExceptionMiddleware", error)
  113. {
  114. Exception = ex,
  115. Message = error
  116. };
  117. ei.Properties["status"] = 1;//走正常返回都是通过走GlobalExceptionFilter不通过
  118. ei.Properties["jsonResult"] = responseResult;
  119. // ei.Properties["requestParam"] = sysOperLog.OperParam;
  120. // ei.Properties["user"] = sysOperLog.OperName;
  121. Logger.Log(ei);
  122. context.Response.ContentType = "text/json;charset=utf-8";
  123. await context.Response.WriteAsync(responseResult, System.Text.Encoding.UTF8);
  124. // string errorMsg = $"> 操作人:{sysOperLog.OperName}" +
  125. // $"\n> 操作地区:{sysOperLog.OperIp}({sysOperLog.OperLocation})" +
  126. // $"\n> 操作模块:{sysOperLog.Title}" +
  127. // $"\n> 操作地址:{sysOperLog.OperUrl}" +
  128. // $"\n> 错误信息:{msg}\n\n> {error}";
  129. // SysOperLogService.InsertOperlog(sysOperLog);
  130. if (!notice) return;
  131. }
  132. public static Endpoint GetEndpoint(HttpContext context)
  133. {
  134. if (context == null)
  135. {
  136. throw new ArgumentNullException(nameof(context));
  137. }
  138. return context.Features.Get<IEndpointFeature>()?.Endpoint;
  139. }
  140. }
  141. }