using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using System.IO; using System.Threading.Tasks; namespace HRD.WebApi.DAL.Middleware { /// /// Gets the current API resource name from HTTP context /// /// The HTTP context /// The current resource name if available, otherwise an empty string public class WebApiMiddleware { private readonly RequestDelegate _next; private readonly ILogger _logger; public WebApiMiddleware(RequestDelegate next, ILogger logger) { _next = next; _logger = logger; } public async Task InvokeAsync(HttpContext httpContext) { try { var loglevel = WebApiConfig.GetMonitoringWebRequestLevel(httpContext.Request.Method, httpContext.Request.Path.Value); if (loglevel == LogLevel.Information || loglevel == LogLevel.Warning || loglevel == LogLevel.Error ) { var requestReader = new StreamReader(httpContext.Request.Body); var requestContent = await requestReader.ReadToEndAsync(); if (string.IsNullOrEmpty(requestContent)) { requestContent = $"{httpContext.Request.Method} {httpContext.Request.Path.Value}"; } if (loglevel == LogLevel.Information) { _logger.LogInformation(requestContent); } if (loglevel == LogLevel.Warning) { _logger.LogWarning(requestContent); } if (loglevel == LogLevel.Error) { _logger.LogError(requestContent); } } } catch (System.Exception) { //throw; } await _next(httpContext).ConfigureAwait(false); } } }