C#C
C#2y ago
Mango

Warning CA1848 : For improved performance, use the LoggerMessage delegates...

Can someone show me how implement LoggerMessage into here? My brain is not connecting the dots:
public class ExceptionFilterMiddleware
{
    private readonly ILogger<ExceptionFilterMiddleware> _logger;
    private readonly RequestDelegate _next;

    public ExceptionFilterMiddleware(ILogger<ExceptionFilterMiddleware> logger, RequestDelegate next)
    {
        _logger = logger;
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        try
        {
            await _next(context);
        }
        catch (Exception ex)
        {
            _logger.LogError("An exception occurred processing the request: {ex}", ex); <-- rule violation here
            context.Response.ContentType = MediaTypeNames.Application.Json;
            context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;

            var json = JsonSerializer.Serialize(new { Message = ex.Message }, context.RequestServices.GetRequiredService<JsonSerializerOptions>());
            await context.Response.WriteAsync(json);
        }
    }
}
Was this page helpful?