Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save LeeCheneler/79bdec70ff84464d71326c00c97a2f6c to your computer and use it in GitHub Desktop.
Save LeeCheneler/79bdec70ff84464d71326c00c97a2f6c to your computer and use it in GitHub Desktop.
Request Header Logging Asp.Net Core Middleware
using System;
using System.Text;
using Microsoft.Extensions.Logging;
namespace Microsoft.AspNetcore.Builder
{
public static class IApplicationBuilderExtensions
{
/// <summary>
/// Logs all request headers
/// </summary>
/// <param name="app"><see cref="IApplicationBuilder"/></param>
/// <param name="loggerFactory"<see cref="ILoggerFactory"/></param>
public static void LogRequestHeaders(this IApplicationBuilder app, ILoggerFactory loggerFactory)
{
var logger = loggerFactory.CreateLogger("Request Headers");
app.Use(async (context, next) =>
{
var builder = new StringBuilder(Environment.NewLine);
foreach (var header in context.Request.Headers)
{
builder.AppendLine($"{header.Key}:{header.Value}");
}
logger.LogTrace(builder.ToString());
await next.Invoke();
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment