中间件不会自动启动,并且不会写入Serilog

问题描述 投票:0回答:1

在这里,我附加了中间件内的代码:

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>();
        }
    }
}

然后,在配置中:

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

以下是我在 NUnit 测试中设置记录器的方法:

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

我注意到中间件根本不起作用。该配置位于一个项目内,稍后需要连接到其他项目。因此,我希望它能够自动配置,如我上面所附的。

为了测试此代码,我使用 NUnit 测试。我尝试抛出异常,但它没有进入中间件。

有人可以提供任何建议或解决方案吗?

c# nunit middleware serilog
1个回答
0
投票

问题是 Nunit 测试无法访问 HttpContext,因为它们是隔离的。事实上,当我发出 HTTP 请求时,它们工作正常。因此,我必须通过调用在测试中手动调用它们。

© www.soinside.com 2019 - 2024. All rights reserved.