This short blog post describes a hack that I implemented to log HTTP request details to the console from ASP.NET Core applications for debugging purposes. If this approach has any value, the logic should be extracted, refactored, and tested.
Update 15.Dec.2025: After years of frustration with WordPress, I am finally abandoning this blog. The content will likely stay here for some time, but new content will appear here:
I add this code just after the if (env.IsDevelopment()) clause in the Startup class.
One of the tricks is that the HTTP body (context.Request.Body) is read-only, so I cannot reset it after reading it. Therefore, this code writes the original body to a memory stream that then replaces that body.
app.Use(async (context, next) =>
{
string msg = context.Request.Protocol
+ " " + context.Request.Method
+ " : " + context.Request.Path;
string sep = new String('-', msg.Length);
Console.WriteLine(sep
+ Environment.NewLine
+ msg
+ Environment.NewLine
+ sep);
foreach (string key in context.Request.Headers.Keys)
{
Console.WriteLine(key + " = "
+ context.Request.Headers[key]);
}
foreach (string key in context.Request.Cookies.Keys)
{
Console.WriteLine(key + " : " + context.Request.Cookies[key]);
}
if (context.Request.Body != null)
{
string body = String.Empty;
using (StreamReader sr =
new StreamReader(context.Request.Body))
{
body = sr.ReadToEndAsync().Result;
}
Console.WriteLine(body);
context.Request.Body =
new MemoryStream(Encoding.UTF8.GetBytes(body));
context.Request.Body.Position = 0;
}
await next.Invoke();
});