123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899 |
- using System;
- using System.Diagnostics;
- using System.Net;
- using System.Security.Claims;
- using System.Threading.Tasks;
- using GxPress.Common.Exceptions;
- using GxPress.Repository.Interface;
- using GxPress.Service.Interface;
- using Microsoft.AspNetCore.Http;
- using Microsoft.Extensions.Logging;
- using Newtonsoft.Json;
- namespace GxPress.Api
- {
- /// <summary>
- /// 自定义异常中间件
- /// </summary>
- public class ExceptionMiddleware
- {
- private readonly RequestDelegate _next;
- private readonly ILogger<ExceptionMiddleware> _logger;
- private readonly IHttpContextAccessor _contextAccessor;
- private readonly IApiLogService _apiLogService;
- public ExceptionMiddleware(RequestDelegate next, ILogger<ExceptionMiddleware> logger, IHttpContextAccessor contextAccessor, IApiLogService _apiLogService)
- {
- _next = next;
- this._apiLogService = _apiLogService;
- _logger = logger;
- _contextAccessor = contextAccessor;
- }
- public async Task Invoke(HttpContext context)
- {
- try
- {
- await _next.Invoke(context);
- // var watch = new Stopwatch();
- // watch.Start();
- if (context.User != null)
- {
- var ty = _contextAccessor?.HttpContext?.User?.FindFirst(ClaimTypes.Role);
- if (ty != null && !ty.Value.Equals("Admin"))
- {
- var userId = _contextAccessor?.HttpContext?.User?.FindFirst(ClaimTypes.NameIdentifier);
- if (int.TryParse(userId?.Value, out var accountId))
- {
- await _apiLogService.DataSave(context, 1, accountId);
- }
- }
- // watch.Stop();
- }
- }
- catch (BusinessException be)
- {
- _logger.LogDebug(be.Message);
- await HandleBusinessException(context, be);
- }
- catch (System.Exception ex)
- {
- _logger.LogError(ex, ex.Message);
- await HandleSystemException(context, ex);
- }
- }
- /// <summary>
- /// 处理业务异常
- /// </summary>
- /// <param name="context"></param>
- /// <param name="be"></param>
- /// <returns></returns>
- private Task HandleBusinessException(HttpContext context, BusinessException be)
- {
- context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
- context.Response.ContentType = "application/json;charset=utf-8";
- return context.Response.WriteAsync(JsonConvert.SerializeObject(new
- {
- be.Message,
- be.StackTrace
- }));
- }
- /// <summary>
- /// 处理系统异常
- /// </summary>
- /// <param name="context"></param>
- /// <param name="ex"></param>
- /// <returns></returns>
- private Task HandleSystemException(HttpContext context, Exception ex)
- {
- context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
- context.Response.ContentType = "application/json;charset=utf-8";
- return context.Response.WriteAsync(JsonConvert.SerializeObject(ex));
- }
- }
- }
|