Created
December 11, 2017 10:45
-
-
Save xumix/3cfb305dfd0f3cb743f9f25908212e4e to your computer and use it in GitHub Desktop.
RequestLoggingMiddleware
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace Pp3.Integration.Host | |
{ | |
using System.IO; | |
using System.Text; | |
using System.Threading.Tasks; | |
using Microsoft.AspNetCore.Http; | |
using Microsoft.Extensions.Logging; | |
public class RequestLoggingMiddleware | |
{ | |
private readonly ILogger<RequestLoggingMiddleware> logger; | |
private readonly RequestDelegate next; | |
public RequestLoggingMiddleware(RequestDelegate next, ILogger<RequestLoggingMiddleware> logger) | |
{ | |
this.next = next; | |
this.logger = logger; | |
} | |
public async Task Invoke(HttpContext context) | |
{ | |
using (var injectedRequestStream = new MemoryStream()) | |
{ | |
var request = context.Request; | |
var requestLog = $"REQUEST HttpMethod: {request.Method}, Path: {request.Path}, Query: {request.QueryString}"; | |
using (var bodyReader = new StreamReader(request.Body)) | |
{ | |
var bodyAsText = bodyReader.ReadToEnd(); | |
if (string.IsNullOrWhiteSpace(bodyAsText) == false) | |
{ | |
requestLog += $", Body : {bodyAsText}"; | |
} | |
var bytesToWrite = Encoding.UTF8.GetBytes(bodyAsText); | |
injectedRequestStream.Write(bytesToWrite, 0, bytesToWrite.Length); | |
injectedRequestStream.Seek(0, SeekOrigin.Begin); | |
request.Body = injectedRequestStream; | |
} | |
logger.LogInformation(requestLog); | |
await next.Invoke(context); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment