Hi @P. G. Choudhury, what you are creating now is a middleware but not an interface, but you are trying to add lifecycle for this middleware which should only be appliable for interface and the implementation.
Middleware is constructed once at application startup when the middleware pipeline is being built. This makes the middleware looks like singleton. But middleware is executed per request. Each request flows through the middleware pipeline, invoking the Invoke
or InvokeAsync
method of each middleware component in sequence and this makes the middleware looks like scoped.
If you want to use middleware to do custom exception dealation, you can use code below and in Program.cs, pls use this middleware by app.UseMiddleware<ExceptionMiddleware>();
.By the way, please use ILogger<ExceptionMiddleware>
instead of ILogger
.
public class ExceptionMiddleware
{
private readonly RequestDelegate _next;
//private readonly ILogger _logger;
private readonly ILogger<ExceptionMiddleware> _logger;
public ExceptionMiddleware(RequestDelegate next, ILogger<ExceptionMiddleware> logger)
{
_logger = logger;
_next = next;
}
public async Task InvokeAsync(HttpContext httpContext)
{
try
{
await _next(httpContext);
}
catch (Exception exp)
{
_logger.LogError($"An unhandled exception has occurred:{exp.GetBaseException}");
await HandleExceptionAsync(httpContext, exp);
}
}
private async Task HandleExceptionAsync(HttpContext httpContext, Exception exp)
{
httpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
httpContext.Response.ContentType = "application/json";
await httpContext.Response.WriteAsync(new ErrorDetails
{
StatusCode = httpContext.Response.StatusCode,
Message = "Internal Server Error from Custom Middleware"
}.ToString());
}
}
And I also find you create ConfigureExceptionHandler
method in your codes, you might want to use IExceptionHandler
to handle known exceptions. You can follow the Microsoft document to drive it.
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Tiny