I have created a middleware which logs requests/response data in the database. I want this middleware to work only when I want to troubleshoot defect or unwanted exception. The middleware should not log rest of the time. I want a switch button which I can on or off on any controller without making any code changes and deployment.
Please suggests the ways to achieve the above.
CodePudding user response:
In Program.cs, you can add conditionally a middleware like :
var builder = WebApplication.CreateBuilder(args);
...
var app = builder.Build();
if (app.Configuration.Get<bool>("MiddlewareLog.Enable"))
{
app.UseCustomeLoggerMiddleware();
}
...
To enable/disable the middleware, you only need to update the appsettings.json and restart the web api/app.
CodePudding user response:
A solution is to enable/disable the middleware from a global setting. Then the controller's action can modify this global setting to enable/disable the middleware.
public class LoggerMiddleware
{
public static volatile bool Enable;
private readonly RequestDelegate _next;
public LoggerMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
if(Enable)
{
// Log
}
await _next(context);
}
}
[Route("logger")]
public class LoggerController : ControllerBase
{
[HttpGet]
public void EnableOrDisable(bool enable)
{
LoggerMiddleware.Enable = enable;
}
}
In the example, I use a static field, but it's possible to inject a singleton service in the middleware and the controller to share the setting.