123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 |
- using Long.Core.Api;
- using Microsoft.AspNetCore.Http;
- using System.Net;
- using System.Text.Json;
- namespace Long.Core.Middleware;
- /// <summary>
- /// 异常捕获中间件
- /// </summary>
- public class LongExceptionCatch
- {
- /// <summary>
- /// 请求委托
- /// </summary>
- private readonly RequestDelegate _requestDelegate;
- public LongExceptionCatch(RequestDelegate requestDelegate)
- {
- _requestDelegate = requestDelegate;
- }
- /// <summary>
- /// 唤起
- /// </summary>
- /// <param name="httpContext"></param>
- /// <returns></returns>
- public async Task Invoke(HttpContext httpContext)
- {
- try
- {
- await _requestDelegate(httpContext);
- }
- catch (Exception ex)
- {
- httpContext.Response.StatusCode = 500;
- httpContext.Response.ContentType = "application/json;charset=utf-8";
- var result = new LongExceptionOutput()
- {
- Success = false,
- Message = "服务器内部错误:" + ex.Message,
- StatusCode = (int)HttpStatusCode.InternalServerError,
- Source = ex.Source ?? "",
- StackTrace = ex.StackTrace ?? "",
- TargetSite = ex.TargetSite,
- Data = ex.Data
- };
- await httpContext.Response.WriteAsync(JsonSerializer.Serialize(result));
- }
- }
- }
|