public class ApiResult
{
public int StatusCode { get; set; }
public object Data { get; set; }
public string Message { get; set; }
}
}
public class GlobalExceptionMiddleware
{
private readonly RequestDelegate _next;
public GlobalExceptionMiddleware(
RequestDelegate next
)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex);
}
}
private static async Task HandleExceptionAsync(HttpContext context, Exception ex)
{
context.Response.ContentType = "application/json";
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
var result = new ApiResult
{
StatusCode = context.Response.StatusCode,
Data = null,
Message = ex.Message
};
await context.Response.WriteAsJsonAsync(result);
}
}