Skip to content

Instantly share code, notes, and snippets.

@djeikyb
Created August 3, 2020 21:18
Show Gist options
  • Save djeikyb/aebf73ccbd4aeafaa9a0abb3110ea794 to your computer and use it in GitHub Desktop.
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
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();
}
}
@djeikyb
Copy link
Author

djeikyb commented Aug 3, 2020

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)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment