using System.Net; using Microsoft.AspNetCore.Mvc; using System.Text.Json; namespace CQRS.WebAPI.Middlewares; public class GlobalExceptionHandlingMiddleware : IMiddleware { private readonly ILogger<GlobalExceptionHandlingMiddleware> _logger; public GlobalExceptionHandlingMiddleware( ILogger<GlobalExceptionHandlingMiddleware> logger) { _logger = logger; } public async Task InvokeAsync(HttpContext context, RequestDelegate next) { try{ await next(context); } catch(Exception e) { _logger.LogError(e.Message); ProblemDetails problem = new() { Status = (int)HttpStatusCode.InternalServerError, Type = "Server error", Title = "Server error", Detail = "An internal server has occurred" }; string json = JsonSerializer.Serialize(problem); context.Response.ContentType = "application/json"; await context.Response.WriteAsync(json); } } }
标签:webapi,处理,Response,json,context,using,返回值,logger,public From: https://www.cnblogs.com/Insist-Y/p/17510088.html