diff --git a/src/WebApiBootstrap.Api/Program.cs b/src/WebApiBootstrap.Api/Program.cs index d610ff9..5d42cd0 100644 --- a/src/WebApiBootstrap.Api/Program.cs +++ b/src/WebApiBootstrap.Api/Program.cs @@ -1,9 +1,14 @@ +using WebApiBootstrap.Contracts.Serialization; + WebApplicationBuilder builder = WebApplication.CreateBuilder(args); // Add services to the container. // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); +builder.Services.ConfigureHttpJsonOptions( + o => MyApiJsonSerializerOptions.Configure(o.SerializerOptions)); + WebApplication app = builder.Build(); app.UseSwagger(); diff --git a/src/WebApiBootstrap.Client/MyApiClient.cs b/src/WebApiBootstrap.Client/MyApiClient.cs index d0278b0..21bb45a 100644 --- a/src/WebApiBootstrap.Client/MyApiClient.cs +++ b/src/WebApiBootstrap.Client/MyApiClient.cs @@ -3,6 +3,9 @@ using System.Net.Http; using Refit; +using WebApiBootstrap.Contracts; +using WebApiBootstrap.Contracts.Serialization; + namespace WebApiBootstrap.Client; public class MyApiClient : IMyApiClient, IDisposable @@ -12,7 +15,14 @@ public class MyApiClient : IMyApiClient, IDisposable public MyApiClient(HttpClient httpClient) { _httpClient = httpClient; - GetWeatherForecast = RestService.For(_httpClient); + var refitSettings = new RefitSettings + { + ContentSerializer + = new SystemTextJsonContentSerializer(MyApiJsonSerializerOptions.Create()) + }; + + GetWeatherForecast + = RestService.For(_httpClient, refitSettings); } public IGetWeatherForecastEndpoint GetWeatherForecast { get; } diff --git a/src/WebApiBootstrap.Contracts/Serialization/MyApiJsonSerializerOptions.cs b/src/WebApiBootstrap.Contracts/Serialization/MyApiJsonSerializerOptions.cs new file mode 100644 index 0000000..8fbd22a --- /dev/null +++ b/src/WebApiBootstrap.Contracts/Serialization/MyApiJsonSerializerOptions.cs @@ -0,0 +1,25 @@ +using System; +using System.Text.Json; +using System.Text.Json.Serialization.Metadata; + +namespace WebApiBootstrap.Contracts.Serialization; + +public static class MyApiJsonSerializerOptions +{ + private static readonly Lazy Instance = new( + () => + { + var options = new JsonSerializerOptions(JsonSerializerDefaults.Web); + Configure(options); + options.TypeInfoResolver = new DefaultJsonTypeInfoResolver(); + options.MakeReadOnly(); + return options; + }); + + public static JsonSerializerOptions Create() => new(Instance.Value); + + public static void Configure(JsonSerializerOptions options) + { + options.WriteIndented = true; + } +} \ No newline at end of file diff --git a/src/WebApiBootstrap.Contracts/WebApiBootstrap.Contracts.csproj b/src/WebApiBootstrap.Contracts/WebApiBootstrap.Contracts.csproj index a06fe4e..a2164ac 100644 --- a/src/WebApiBootstrap.Contracts/WebApiBootstrap.Contracts.csproj +++ b/src/WebApiBootstrap.Contracts/WebApiBootstrap.Contracts.csproj @@ -14,6 +14,7 @@ + \ No newline at end of file