Hello,
I am trying to implement middleware to handle exceptions globally in a .NetCore WebAPI project. My .NetCore version is 9.0. Full details of the exception that is being thrown when I'm trying to launch my webAPI is as:
InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Http.RequestDelegate' while attempting to activate 'Stack9Backend.CustomExceptionMiddleware.GlobalExceptionHandlingMiddleware'.
What I did was, create a custom middleware class extending from IMiddleware. The implementation is as:
public class GlobalExceptionHandlingMiddleware:IMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<GlobalExceptionHandlingMiddleware> _logger;
public GlobalExceptionHandlingMiddleware(RequestDelegate next, ILogger<GlobalExceptionHandlingMiddleware> logger)
{
_next = next;
_logger = logger;
}
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
try
{
await next(context);
}
catch (Exception ex)
{
_logger.LogError(ex, ex.Message);
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
ProblemDetails problem = new()
{
Status = (int)HttpStatusCode.InternalServerError,
Type = "Backend Server Error",
Title = "Backend Server Error",
Detail = "An unexpected server error occurred"
};
string json=JsonSerializer.Serialize(problem);
await context.Response.WriteAsync(json);
context.Response.ContentType = "application/json";
}
}
}
Here ILogger comes from Microsoft.Extensions.Logging. To use this middleware I applied it in my Program.cs as:
builder.Services.AddTransient<GlobalExceptionHandlingMiddleware>();
var app = builder.Build(); <------ exception thrown on this line
app.UseMiddleware<GlobalExceptionHandlingMiddleware>();
I tried AddSingleton also in place of AddTransient. That didn't work.
I thought since my middleware implements IMiddleware, so I also tried -->
builder.Services.AddScoped<IMiddleware, GlobalExceptionHandlingMiddleware>();
But no. None of the above tweaks worked. Been stuck with this for a considerable amount of time now. Looking for some help on this.
Thanks