From e2f75fb4ddce69f361c533a6f4bd55d85b2eeae3 Mon Sep 17 00:00:00 2001 From: xiang <27800734@qq.com> Date: Sun, 11 May 2025 17:40:51 +0800 Subject: [PATCH] 1 --- .../GlobalExceptionHandlerMiddleware.cs | 39 +++++++++++-------- 1 file changed, 23 insertions(+), 16 deletions(-) diff --git a/Yes.Infrastructure/Middlewares/GlobalExceptionHandlerMiddleware.cs b/Yes.Infrastructure/Middlewares/GlobalExceptionHandlerMiddleware.cs index 09f3aa9..eb18af6 100644 --- a/Yes.Infrastructure/Middlewares/GlobalExceptionHandlerMiddleware.cs +++ b/Yes.Infrastructure/Middlewares/GlobalExceptionHandlerMiddleware.cs @@ -19,8 +19,12 @@ private async Task HandleExceptionAsync(HttpContext context, Exception ex) { - context.Response.ContentType = "application/problem+json"; - context.Response.StatusCode = StatusCodes.Status500InternalServerError; + if (!context.Response.HasStarted) + { + context.Response.ContentType = "application/problem+json"; + context.Response.StatusCode = StatusCodes.Status500InternalServerError; + } + var title = ""; var message = ""; var exType = ex.GetType(); @@ -50,22 +54,25 @@ _logger.LogError(ex, "Exception"); } - var acceptHeader = context.Request.Headers["Accept"].FirstOrDefault(); - var isAjaxRequest = acceptHeader?.Contains("application/json") == true; - if (isAjaxRequest) + if (!context.Response.HasStarted) { - var problem = new ProblemDetails + var acceptHeader = context.Request.Headers["Accept"].FirstOrDefault(); + var isAjaxRequest = acceptHeader?.Contains("application/json") == true; + if (isAjaxRequest) { - Status = StatusCodes.Status500InternalServerError, - Title = title, - Type = "https://tools.ietf.org/html/rfc7231#section-6.5.1", - Detail = message - }; - await context.Response.WriteAsJsonAsync(problem); - } - else - { - await context.Response.WriteAsync(message); + var problem = new ProblemDetails + { + Status = StatusCodes.Status500InternalServerError, + Title = title, + Type = "https://tools.ietf.org/html/rfc7231#section-6.5.1", + Detail = message + }; + await context.Response.WriteAsJsonAsync(problem); + } + else + { + await context.Response.WriteAsync(message); + } } }