using IM.Commons; using IM.DomainCommons; using Microsoft.AspNetCore.Http; namespace IM.ASPNETCore { public class ExceptionMiddleware { private readonly RequestDelegate _next; public ExceptionMiddleware(RequestDelegate next) { _next = next; } public async Task InvokeAsync(HttpContext context) { try { await _next(context); } catch (DomainException ex) { await DomainExceptionHandlerAsync(context, ex); } } public Task DomainExceptionHandlerAsync(HttpContext context, DomainException ex) { context.Response.ContentType = "application/json"; var result = Result.Fail(ResultCode.PARAMETER_ERROR, ex.Message); // 包装成你的 Result return context.Response.WriteAsJsonAsync(result); } } }