From bed50d7419f9de2162a4d785bc4c57ad5f33ca96 Mon Sep 17 00:00:00 2001 From: maliming Date: Wed, 30 Jul 2025 17:36:41 +0800 Subject: [PATCH] Add LoggingHandler to log HTTP requests. --- src/EventHub.Web/EventHubWebModule.cs | 15 +++++++++------ src/EventHub.Web/LoggingHandler.cs | 27 +++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 6 deletions(-) create mode 100644 src/EventHub.Web/LoggingHandler.cs diff --git a/src/EventHub.Web/EventHubWebModule.cs b/src/EventHub.Web/EventHubWebModule.cs index 124bb4c..c002292 100644 --- a/src/EventHub.Web/EventHubWebModule.cs +++ b/src/EventHub.Web/EventHubWebModule.cs @@ -1,5 +1,6 @@ using System; using System.IO; +using System.Net.Http; using EventHub.Localization; using EventHub.Options; using EventHub.Web.Menus; @@ -89,7 +90,7 @@ namespace EventHub.Web ConfigureSwaggerServices(context.Services); ConfigureRazorPageOptions(); } - + private void ConfigureBundles() { Configure(options => @@ -118,7 +119,7 @@ namespace EventHub.Web { options.Applications["MVC"].RootUrl = EventHubUrlOptions.GetWwwConfigValue(configuration); }); - + Configure(options => { options.RemoteServices.Default = new RemoteServiceConfiguration( @@ -127,7 +128,7 @@ namespace EventHub.Web ); }); } - + private void ConfigureRazorPageOptions() { Configure(options => @@ -169,9 +170,11 @@ namespace EventHub.Web options.Scope.Add("email"); options.Scope.Add("phone"); options.Scope.Add("EventHub"); + + options.BackchannelHttpHandler = new LoggingHandler(); }); } - + private void ConfigureAutoMapper() { Configure(options => @@ -206,7 +209,7 @@ namespace EventHub.Web options.Contributors.Add(new EventHubToolbarContributor()); }); } - + private void ConfigureCookies(ServiceConfigurationContext context) { context.Services.AddSameSiteCookiePolicy(); @@ -238,7 +241,7 @@ namespace EventHub.Web { var app = context.GetApplicationBuilder(); var env = context.GetEnvironment(); - + app.Use((context, next) => { context.Request.Scheme = "https"; diff --git a/src/EventHub.Web/LoggingHandler.cs b/src/EventHub.Web/LoggingHandler.cs new file mode 100644 index 0000000..0335927 --- /dev/null +++ b/src/EventHub.Web/LoggingHandler.cs @@ -0,0 +1,27 @@ +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +using Serilog; + +namespace EventHub.Web; + +public class LoggingHandler : DelegatingHandler +{ + public LoggingHandler() + : base(new HttpClientHandler()) + { + } + + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + Log.Error($"[Request] {request.Method} {request.RequestUri}"); + if (request.Method == HttpMethod.Post && request.Content != null) + { + var content = await request.Content.ReadAsStringAsync(cancellationToken); + Log.Error($"[Request Content Headers] {request.Content.Headers}"); + Log.Error($"[Request Content] {content}"); + } + + return await base.SendAsync(request, cancellationToken); + } +}