@@ -4,21 +4,30 @@ namespace Devpro.TerraformBackend.WebApi.DependencyInjection;
44
55internal static class BehaviorServiceCollectionExtensions
66{
7- internal static IServiceCollection AddBehaviors ( this IServiceCollection services )
7+ /// <summary>
8+ /// Ensures that every time an invalid model state occurs in the API, a warning log is generated with the request path.
9+ /// </summary>
10+ /// <param name="services"></param>
11+ /// <returns></returns>
12+ internal static IServiceCollection AddInvalidModelStateLog ( this IServiceCollection services )
813 {
914 services . PostConfigure < ApiBehaviorOptions > ( options =>
1015 {
11- var builtInFactory = options . InvalidModelStateResponseFactory ;
16+ var defaultFactory = options . InvalidModelStateResponseFactory ;
1217
1318 options . InvalidModelStateResponseFactory = context =>
1419 {
1520 var loggerFactory = context . HttpContext . RequestServices
1621 . GetRequiredService < ILoggerFactory > ( ) ;
17- var logger = loggerFactory . CreateLogger ( "PostConfigure" ) ;
22+ var logger = loggerFactory . CreateLogger ( nameof ( BehaviorServiceCollectionExtensions ) ) ;
1823
19- logger . LogWarning ( "Invalid model {RequestPath}" , context . HttpContext . Request . Path ) ;
24+ var errors = context . ModelState
25+ . Where ( m => m . Value ? . Errors . Any ( ) == true )
26+ . Select ( m => new { Field = m . Key , Errors = m . Value ! . Errors . Select ( e => e . ErrorMessage ) } ) ;
2027
21- return builtInFactory ( context ) ;
28+ logger . LogWarning ( "Invalid model state for {RequestPath}. Validation errors {@ModelErrors}" , context . HttpContext . Request . Path , errors ) ;
29+
30+ return defaultFactory ( context ) ;
2231 } ;
2332 } ) ;
2433
0 commit comments