Created
August 3, 2020 21:18
-
-
Save djeikyb/aebf73ccbd4aeafaa9a0abb3110ea794 to your computer and use it in GitHub Desktop.
example of intercepting a request and logging the body and all its headers, dotnet core 3.0
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
public class InterceptAndDebugRequestMiddleware : IMiddleware | |
{ | |
private readonly LogProps _props; | |
public InterceptAndDebugRequestMiddleware(LogProps props) | |
{ | |
_props = props; | |
} | |
public async Task InvokeAsync(HttpContext context, RequestDelegate next) | |
{ | |
if (!context.Request.Path.ToUriComponent().StartsWith("/some/route")) | |
{ | |
await next(context); | |
return; | |
} | |
_props.Add("request.method", context.Request.Method); | |
foreach (var (headerName, headerValues) in context.Request.Headers) | |
{ | |
for (var i = 0; i < headerValues.Count; i++) | |
{ | |
string headerValue = string.Equals(headerName, "Authorization", StringComparison.OrdinalIgnoreCase) | |
? "redacted" | |
: headerValues[i]; | |
_props.Add($"request.header.{headerName}[{i}]", headerValue); | |
} | |
} | |
if (context.Request.Body != null) | |
{ | |
using var sr = new StreamReader(context.Request.Body); | |
var body = await sr.ReadToEndAsync(); | |
if (body != string.Empty) | |
{ | |
_props.Add("request.body", body); | |
} | |
} | |
await context.Response.CompleteAsync(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
presumes the existence of a LogProps object injected with a scoped lifetime, and a middleware that puts all the collected properties into a log event (like with serilog's LogContext)