using Microsoft.AspNetCore.Http; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text.Json; using System.Threading.Tasks; using Common; using Common.Tools; namespace djy_IsfApi { /* 使用方法 在startup Configure中添加 app.UseMiddleware(); */ /// /// 访问管道 /// public class MytMiddleware { /// /// /// private readonly RequestDelegate next; public MytMiddleware(RequestDelegate next) { this.next = next; } /// /// /// /// /// public async Task Invoke(HttpContext context) { try { await next(context); } catch (Exception ex) { await HandleExceptionAsync(context, ex); } finally { var statuscode = context.Response.StatusCode; var h = context.Response.HasStarted; ReturnResult rr = new ReturnResult(); if (statuscode == 401|| statuscode == 400) { //页面的状态码 根据需求调整是否修改 switch (statuscode) { case 400: rr.Message = "请求错误!"; rr.Code = 400; break; case 401: rr.Message = "授权验证失败或已过期,请重新登录"; rr.Code = 401; break; } rr.Status = false; var response = context.Response; try { response.StatusCode = 200; } catch (Exception ex) { var msg = ex.Message; } response.ContentType = "application/json"; await response.WriteAsync(JsonSerializer.Serialize(rr, new JsonSerializerOptions(JsonSerializerDefaults.Web))).ConfigureAwait(false); /* * 响应格式: { "code": 401, "Status": false, "message": "授权验证失败或已过期,请重新登录", "getTime": 1703135086, "runTime": 1238.5565, "data": null, "memoData": null } */ } } } /// /// /// /// /// /// private static async Task HandleExceptionAsync(HttpContext context, Exception exception) { if (exception == null) return; await WriteExceptionAsync(context, exception).ConfigureAwait(false); } /// /// /// /// /// /// private static async Task WriteExceptionAsync(HttpContext context, Exception exception) { //记录日志 //返回友好的提示 var response = context.Response; //状态码 if (exception is UnauthorizedAccessException) response.StatusCode = (int)HttpStatusCode.Unauthorized; else if (exception is Exception) response.StatusCode = (int)HttpStatusCode.BadRequest; response.ContentType = context.Request.Headers["Accept"]; response.StatusCode = 200; string msg = string.Format("内部错误:{0}", exception.GetBaseException().Message); try { var json = JsonSerializer.Serialize(exception.GetBaseException()); Tools.ServerWarnMessageErr(msg + " " + json); } catch { } ReturnResult rr = new ReturnResult(); rr.Code = 400; rr.Status = false; rr.Message = msg; rr.Data = rr.Message; response.ContentType = "application/json"; await response.WriteAsync(JsonSerializer.Serialize(rr, new JsonSerializerOptions(JsonSerializerDefaults.Web))).ConfigureAwait(false); } } }