marco.pms.api/Marco.Pms.Services/Middleware/ExceptionHandlingMiddleware.cs

42 lines
1.2 KiB
C#

namespace MarcoBMS.Services.Middleware
{
public class ExceptionHandlingMiddleware
{
private readonly RequestDelegate _next;
public ExceptionHandlingMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
try
{
context.Response.Headers.Remove("X-Powered-By");
context.Response.Headers.Remove("Server");
await _next(context);
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex);
}
}
private Task HandleExceptionAsync(HttpContext context, Exception exception)
{
var response = new
{
message = exception.Message,
detail = exception.StackTrace,
statusCode = StatusCodes.Status500InternalServerError
};
context.Response.ContentType = "application/json";
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
return context.Response.WriteAsJsonAsync(response);
}
}
}