Search code examples
c#nunitmiddlewareserilog

The middleware doesn't start automatically, and it doesn't write to Serilog


Here, I'm attaching the code inside the middleware:

namespace ...
{
    public class MyMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger _logger;

        public MyMiddleware(RequestDelegate next, ILogger logger)
        {
            _next = next;
            _logger = logger;
        }

        public async Task Invoke(HttpContext context)
        {
            Log.Information("::::::MyMiddleware executing");

            try
            {
                 _logger.LogInformation("MyMiddleware executing..");
                await _next(context);
            }
            catch (Exception ex)
            {
                await HandleExceptionAsync(context, ex);
            }
        }

        private Task HandleExceptionAsync(HttpContext context, Exception ex)
        {
            _logger.LogError(ex.Message + "ERROR Exc...");

            Log.Error(ex.Message + "ERROR Exc...");

            var errorid = Activity.Current?.Id ?? context.TraceIdentifier;
            var customerError = $"ErrorId-{errorid}: Message-Some kind of error happened in the API";
            var result = JsonConvert.SerializeObject(customerError);
            context.Response.ContentType = "application/json";
            context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            return context.Response.WriteAsync(result);
        }
    }

    public static class MyMiddlewareExtensions
    {
        public static IApplicationBuilder UseMyMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<MyMiddleware>();
        }
    }
}

And then, here in the configuration:

webBuilder.Configure(app =>
{
    app.UseMyMiddleware();
});

Here's how I set up the logger inside the NUnit test:

Log.Logger = new LoggerConfiguration()
                    .WriteTo.File("logs\\log.txt", rollingInterval: RollingInterval.Day) // Log su file
                    .CreateLogger();

I'm noticing that the middleware isn't working at all. The configuration is within a project that will later need to connect to other projects. So, I would like it to be automatically configured as I have attached above.

To test this code, I'm using NUnit tests. I've tried throwing an exception, but it doesn't enter the middleware.

Does anyone have any advice or a solution to offer?


Solution

  • The issue was that Nunit tests cannot access HttpContext because they are isolated. In fact, when I made an HTTP request, they worked correctly. So, I had to manually invoke them within the tests by making calls.