Hi @P. G. Choudhury,The reason why you get the error when running the application for the var app = builder.Build();
is the Middleware should not be registered as a singleton, you should directly use it instead of register it.
This is not a service.
The second error for your codes is the incorrect logger injection, in your ExceptionMiddleware constructor, you are directly injecting ILogger. However, ILogger is a generic interface that is intended to be used as ILogger<T>, where T is typically the class type in which it’s being used.
The third issue is you use the duplicate exception handling.You’re configuring both app.UseExceptionHandler and custom middleware (ExceptionMiddleware). They serve similar purposes but handle exceptions in different ways. Typically, you should choose one or the other.
I suggest you could try modify your codes as below and then test again.
1.Modify the ExceptionMiddleware to set the logger well.
public class ExceptionMiddleware
{
private readonly RequestDelegate _next;
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("test");
}
}
2.Modify the ExceptionMiddlewareExtensions class as below:
public static class ExceptionMiddlewareExtensions
{
public static void ConfigureCustomExceptionMiddleware(this WebApplication app)
{
app.UseMiddleware<ExceptionMiddleware>();
}
}
3.Directly use it inside the program.cs:
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
builder.Services.AddOpenApi();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.MapOpenApi();
}
app.ConfigureCustomExceptionMiddleware(); // Use custom exception middleware here.
app.UseHttpsRedirection();
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.