From c801e599ea4e44d3fce3b60460412245d650ddd4 Mon Sep 17 00:00:00 2001 From: Young Date: Tue, 8 Oct 2024 22:17:41 +0800 Subject: [PATCH] added controllers configuration --- .../Extensions/ControllerSetup.cs | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 src/Infrastructure/Extensions/ControllerSetup.cs diff --git a/src/Infrastructure/Extensions/ControllerSetup.cs b/src/Infrastructure/Extensions/ControllerSetup.cs new file mode 100644 index 0000000..faf9d9a --- /dev/null +++ b/src/Infrastructure/Extensions/ControllerSetup.cs @@ -0,0 +1,40 @@ +using Infrastructure.Filters; +using Infrastructure.Utils; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.DependencyInjection; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Serialization; + +namespace Infrastructure.Extensions; + +public static class ControllerSetup +{ + public static IServiceCollection AddDefaultControllers(this IServiceCollection services) + { + 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 => + { + options.InvalidModelStateResponseFactory = context => + { + var message = new MessageData(false, "the input wat not valid", 400); + return new OkObjectResult(message.Serialize()); + }; + }); + return services; + } +} \ No newline at end of file