ASP.NET Core: Dump HTTP Request Data to Console

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.

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.

I do not understand why it needs to call await next.Invoke(); at the end; I would expect the middleware pipeline to simply continue without this call.

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();
});

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: