From 4cae00bd860a7b44036612065e1ce6d1cf068b7f Mon Sep 17 00:00:00 2001 From: Young Date: Tue, 22 Oct 2024 21:27:07 +0800 Subject: [PATCH] enhance configure controllers --- .../Extensions/ControllerSetup.cs | 48 ++++++++++--------- 1 file changed, 26 insertions(+), 22 deletions(-) diff --git a/src/Infrastructure/Extensions/ControllerSetup.cs b/src/Infrastructure/Extensions/ControllerSetup.cs index 5050d8e..95e99f0 100644 --- a/src/Infrastructure/Extensions/ControllerSetup.cs +++ b/src/Infrastructure/Extensions/ControllerSetup.cs @@ -13,32 +13,36 @@ public static class ControllerSetup /// 配置controller,包含过滤器、json序列化以及模型验证等配置 /// /// + /// /// - public static IServiceCollection AddDefaultControllers(this IServiceCollection services) + public static IServiceCollection AddDefaultControllers(this IServiceCollection services, + Action? configureControllers = null) { ArgumentNullException.ThrowIfNull(services); - services.AddControllers(options => - { - options.Filters.Add(); - options.Filters.Add(); - }) - .AddNewtonsoftJson(options => - { - options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; - options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); - options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss"; - options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local; - options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore; - options.SerializerSettings.Converters.Add(new StringEnumConverter()); - }) - .ConfigureApiBehaviorOptions(options => + var mvcBuilder = services.AddControllers(options => + { + options.Filters.Add(); + options.Filters.Add(); + }); + + mvcBuilder.AddNewtonsoftJson(options => + { + options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; + options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); + options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss"; + options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local; + options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore; + options.SerializerSettings.Converters.Add(new StringEnumConverter()); + }); + mvcBuilder.ConfigureApiBehaviorOptions(options => + { + options.InvalidModelStateResponseFactory = _ => { - options.InvalidModelStateResponseFactory = _ => - { - var message = new MessageData(false, "the input value not valid", 400); - return new OkObjectResult(message.Serialize()); - }; - }); + var message = new MessageData(false, "the input value not valid", 400); + return new OkObjectResult(message.Serialize()); + }; + }); + configureControllers?.Invoke(mvcBuilder); return services; } } \ No newline at end of file