From d8c606f37ef9ce9c7f95e6b0ba500a935994876e Mon Sep 17 00:00:00 2001 From: Mohsen Rajabi Date: Tue, 16 Jul 2024 00:29:36 +0330 Subject: [PATCH 01/26] feat: rm newtonsoft --- .../ConsulFileConfigurationRepository.cs | 7 +- .../DiskFileConfigurationRepository.cs | 11 +-- .../Repository/FileConfigurationPoller.cs | 7 +- .../ConfigurationBuilderExtensions.cs | 12 +-- .../DependencyInjection/OcelotBuilder.cs | 3 +- .../JsonSerializerOptionsExtensions.cs | 33 +++++++++ .../Metadata/DownstreamRouteExtensions.cs | 4 +- .../Multiplexer/MultiplexingMiddleware.cs | 21 ++++-- src/Ocelot/Ocelot.csproj | 2 + .../DistributedCacheRateLimitStorage.cs | 7 +- src/Ocelot/RateLimiting/RateLimitCounter.cs | 4 +- src/Ocelot/Requester/MessageInvokerPool.cs | 2 +- test/Ocelot.AcceptanceTests/BearerToken.cs | 8 +- .../Caching/CachingTests.cs | 5 +- .../ConfigurationInConsulTests.cs | 8 +- .../ConsulConfigurationInConsulTests.cs | 12 +-- .../ConsulServiceDiscoveryTests.cs | 10 ++- .../ServiceDiscovery/ConsulWebSocketTests.cs | 3 +- .../EurekaServiceDiscoveryTests.cs | 52 ++++++------- .../KubernetesServiceDiscoveryTests.cs | 5 +- test/Ocelot.AcceptanceTests/Steps.cs | 74 ++++++++++--------- .../TwoDownstreamServicesTests.cs | 5 +- .../AllTheThingsBenchmarks.cs | 5 +- test/Ocelot.Benchmarks/MsLoggerBenchmarks.cs | 5 +- test/Ocelot.Benchmarks/PayloadBenchmarks.cs | 7 +- test/Ocelot.Benchmarks/ResponseBenchmarks.cs | 6 +- test/Ocelot.Benchmarks/SerilogBenchmarks.cs | 5 +- .../AdministrationTests.cs | 17 +++-- test/Ocelot.IntegrationTests/BearerToken.cs | 7 +- .../CacheManagerTests.cs | 7 +- test/Ocelot.IntegrationTests/HeaderTests.cs | 5 +- .../ThreadSafeHeadersTests.cs | 5 +- test/Ocelot.IntegrationTests/ocelot.json | 2 +- .../CustomOcelotMiddleware.cs | 5 +- .../DiskFileConfigurationRepositoryTests.cs | 11 +-- .../ConsulFileConfigurationRepositoryTests.cs | 11 +-- test/Ocelot.UnitTests/Consul/ConsulTests.cs | 5 +- .../ConfigurationBuilderExtensionsTests.cs | 7 +- .../DependencyInjection/OcelotBuilderTests.cs | 14 +--- test/Ocelot.UnitTests/Kubernetes/KubeTests.cs | 5 +- .../Requester/MessageInvokerPoolTests.cs | 2 +- 41 files changed, 244 insertions(+), 182 deletions(-) create mode 100644 src/Ocelot/Infrastructure/JsonSerializerOptionsExtensions.cs diff --git a/src/Ocelot.Provider.Consul/ConsulFileConfigurationRepository.cs b/src/Ocelot.Provider.Consul/ConsulFileConfigurationRepository.cs index c95146f46..79937962f 100644 --- a/src/Ocelot.Provider.Consul/ConsulFileConfigurationRepository.cs +++ b/src/Ocelot.Provider.Consul/ConsulFileConfigurationRepository.cs @@ -1,13 +1,14 @@ using Microsoft.Extensions.Options; -using Newtonsoft.Json; using Ocelot.Cache; using Ocelot.Configuration; using Ocelot.Configuration.File; using Ocelot.Configuration.Repository; +using Ocelot.Infrastructure; using Ocelot.Logging; using Ocelot.Provider.Consul.Interfaces; using Ocelot.Responses; using System.Text; +using System.Text.Json; namespace Ocelot.Provider.Consul; @@ -53,14 +54,14 @@ public async Task> Get() var bytes = queryResult.Response.Value; var json = Encoding.UTF8.GetString(bytes); - var consulConfig = JsonConvert.DeserializeObject(json); + var consulConfig = JsonSerializer.Deserialize(json, JsonSerializerOptionsExtensions.Web); return new OkResponse(consulConfig); } public async Task Set(FileConfiguration ocelotConfiguration) { - var json = JsonConvert.SerializeObject(ocelotConfiguration, Formatting.Indented); + var json = JsonSerializer.Serialize(ocelotConfiguration, JsonSerializerOptionsExtensions.WebWriteIndented); var bytes = Encoding.UTF8.GetBytes(json); var kvPair = new KVPair(_configurationKey) { diff --git a/src/Ocelot/Configuration/Repository/DiskFileConfigurationRepository.cs b/src/Ocelot/Configuration/Repository/DiskFileConfigurationRepository.cs index 56933a5f2..e3935b4b9 100644 --- a/src/Ocelot/Configuration/Repository/DiskFileConfigurationRepository.cs +++ b/src/Ocelot/Configuration/Repository/DiskFileConfigurationRepository.cs @@ -1,9 +1,10 @@ using Microsoft.AspNetCore.Hosting; -using Newtonsoft.Json; using Ocelot.Configuration.ChangeTracking; using Ocelot.Configuration.File; using Ocelot.DependencyInjection; +using Ocelot.Infrastructure; using Ocelot.Responses; +using System.Text.Json; using FileSys = System.IO.File; namespace Ocelot.Configuration.Repository; @@ -49,14 +50,14 @@ public Task> Get() jsonConfiguration = FileSys.ReadAllText(_environmentFile.FullName); } - var fileConfiguration = JsonConvert.DeserializeObject(jsonConfiguration); + var fileConfiguration = JsonSerializer.Deserialize(jsonConfiguration, JsonSerializerOptionsExtensions.Web); return Task.FromResult>(new OkResponse(fileConfiguration)); } - public Task Set(FileConfiguration fileConfiguration) - { - var jsonConfiguration = JsonConvert.SerializeObject(fileConfiguration, Formatting.Indented); + public Task Set(FileConfiguration fileConfiguration) + { + var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsExtensions.WebWriteIndented); lock (_lock) { diff --git a/src/Ocelot/Configuration/Repository/FileConfigurationPoller.cs b/src/Ocelot/Configuration/Repository/FileConfigurationPoller.cs index cfea4dca5..ec6445bf3 100644 --- a/src/Ocelot/Configuration/Repository/FileConfigurationPoller.cs +++ b/src/Ocelot/Configuration/Repository/FileConfigurationPoller.cs @@ -1,8 +1,9 @@ using Microsoft.Extensions.Hosting; -using Newtonsoft.Json; using Ocelot.Configuration.Creator; using Ocelot.Configuration.File; +using Ocelot.Infrastructure; using Ocelot.Logging; +using System.Text.Json; namespace Ocelot.Configuration.Repository; @@ -68,7 +69,7 @@ private async Task Poll() if (fileConfig.IsError) { - _logger.LogWarning(() =>$"error geting file config, errors are {string.Join(',', fileConfig.Errors.Select(x => x.Message))}"); + _logger.LogWarning(() => $"error geting file config, errors are {string.Join(',', fileConfig.Errors.Select(x => x.Message))}"); return; } @@ -95,7 +96,7 @@ private async Task Poll() /// hash of the config. private static string ToJson(FileConfiguration config) { - var currentHash = JsonConvert.SerializeObject(config); + var currentHash = JsonSerializer.Serialize(config, JsonSerializerOptionsExtensions.Web); return currentHash; } diff --git a/src/Ocelot/DependencyInjection/ConfigurationBuilderExtensions.cs b/src/Ocelot/DependencyInjection/ConfigurationBuilderExtensions.cs index f07baba1a..99aa1a507 100644 --- a/src/Ocelot/DependencyInjection/ConfigurationBuilderExtensions.cs +++ b/src/Ocelot/DependencyInjection/ConfigurationBuilderExtensions.cs @@ -1,9 +1,9 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration.Memory; -using Newtonsoft.Json; using Ocelot.Configuration.File; using Ocelot.Infrastructure; +using System.Text.Json; namespace Ocelot.DependencyInjection; @@ -133,7 +133,7 @@ private static string GetMergedOcelotJson(string folder, IWebHostEnvironment env } var lines = File.ReadAllText(file.FullName); - var config = JsonConvert.DeserializeObject(lines); + var config = JsonSerializer.Deserialize(lines, JsonSerializerOptionsExtensions.Web); if (file.Name.Equals(globalFileInfo.Name, StringComparison.OrdinalIgnoreCase) && file.FullName.Equals(globalFileInfo.FullName, StringComparison.OrdinalIgnoreCase)) { @@ -144,9 +144,9 @@ private static string GetMergedOcelotJson(string folder, IWebHostEnvironment env fileConfiguration.Routes.AddRange(config.Routes); } - return JsonConvert.SerializeObject(fileConfiguration, Formatting.Indented); - } - + return JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsExtensions.WebWriteIndented); + } + /// /// Adds Ocelot configuration by ready configuration object and writes JSON to the primary configuration file.
/// Finally, adds JSON file as configuration provider. @@ -161,7 +161,7 @@ private static string GetMergedOcelotJson(string folder, IWebHostEnvironment env public static IConfigurationBuilder AddOcelot(this IConfigurationBuilder builder, FileConfiguration fileConfiguration, string primaryConfigFile = null, bool? optional = null, bool? reloadOnChange = null) // optional injections { - var json = JsonConvert.SerializeObject(fileConfiguration, Formatting.Indented); + var json = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsExtensions.WebWriteIndented); return AddOcelotJsonFile(builder, json, primaryConfigFile, optional, reloadOnChange); } diff --git a/src/Ocelot/DependencyInjection/OcelotBuilder.cs b/src/Ocelot/DependencyInjection/OcelotBuilder.cs index 5d152cd77..4ec131d79 100644 --- a/src/Ocelot/DependencyInjection/OcelotBuilder.cs +++ b/src/Ocelot/DependencyInjection/OcelotBuilder.cs @@ -183,8 +183,7 @@ protected IMvcCoreBuilder AddDefaultAspNetServices(IMvcCoreBuilder builder, Asse return builder .AddApplicationPart(assembly) .AddControllersAsServices() - .AddAuthorization() - .AddNewtonsoftJson(); + .AddAuthorization(); } public IOcelotBuilder AddSingletonDefinedAggregator() diff --git a/src/Ocelot/Infrastructure/JsonSerializerOptionsExtensions.cs b/src/Ocelot/Infrastructure/JsonSerializerOptionsExtensions.cs new file mode 100644 index 000000000..b3c0fb526 --- /dev/null +++ b/src/Ocelot/Infrastructure/JsonSerializerOptionsExtensions.cs @@ -0,0 +1,33 @@ +using System.Text.Encodings.Web; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Text.Unicode; + +namespace Ocelot.Infrastructure +{ + public static class JsonSerializerOptionsExtensions + { + public static readonly JsonSerializerOptions Web = new() + { + PropertyNameCaseInsensitive = true, + //PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + //DictionaryKeyPolicy = JsonNamingPolicy.CamelCase, + NumberHandling = JsonNumberHandling.AllowReadingFromString, + ReferenceHandler = ReferenceHandler.IgnoreCycles, + WriteIndented = false, + Encoder = JavaScriptEncoder.Create(UnicodeRanges.All), + + }; + + public static readonly JsonSerializerOptions WebWriteIndented = new() + { + PropertyNameCaseInsensitive = true, + //PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + //DictionaryKeyPolicy = JsonNamingPolicy.CamelCase, + NumberHandling = JsonNumberHandling.AllowReadingFromString, + ReferenceHandler = ReferenceHandler.IgnoreCycles, + WriteIndented = true, + Encoder = JavaScriptEncoder.Create(UnicodeRanges.All) + }; + } +} diff --git a/src/Ocelot/Metadata/DownstreamRouteExtensions.cs b/src/Ocelot/Metadata/DownstreamRouteExtensions.cs index ca3ba25e6..b9c351f0c 100644 --- a/src/Ocelot/Metadata/DownstreamRouteExtensions.cs +++ b/src/Ocelot/Metadata/DownstreamRouteExtensions.cs @@ -1,6 +1,6 @@ using Ocelot.Configuration; +using Ocelot.Infrastructure; using System.Globalization; -using System.Reflection; using System.Text.Json; namespace Ocelot.Metadata; @@ -74,7 +74,7 @@ public static T GetMetadata(this DownstreamRoute downstreamRoute, string key, } return (T)ConvertTo(typeof(T), metadataValue, downstreamRoute.MetadataOptions, - jsonSerializerOptions ?? new JsonSerializerOptions(JsonSerializerDefaults.Web)); + jsonSerializerOptions ?? JsonSerializerOptionsExtensions.Web); } /// diff --git a/src/Ocelot/Multiplexer/MultiplexingMiddleware.cs b/src/Ocelot/Multiplexer/MultiplexingMiddleware.cs index c148eb9b9..281f14f58 100644 --- a/src/Ocelot/Multiplexer/MultiplexingMiddleware.cs +++ b/src/Ocelot/Multiplexer/MultiplexingMiddleware.cs @@ -1,12 +1,14 @@ +using Json.Path; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Primitives; -using Newtonsoft.Json.Linq; using Ocelot.Configuration; using Ocelot.Configuration.File; using Ocelot.DownstreamRouteFinder.UrlMatcher; using Ocelot.Logging; using Ocelot.Middleware; using System.Collections; +using System.Text.Json; +using System.Text.Json.Nodes; using Route = Ocelot.Configuration.Route; namespace Ocelot.Multiplexer; @@ -132,14 +134,15 @@ protected virtual async Task ProcessRoutesWithRouteKeysAsync(Http { var processing = new List>(); var content = await mainResponse.Items.DownstreamResponse().Content.ReadAsStringAsync(); - var jObject = JToken.Parse(content); + var jObject = JsonDocument.Parse(content); + var jNode = JsonNode.Parse(content); foreach (var downstreamRoute in routes.Skip(1)) { var matchAdvancedAgg = routeKeysConfigs.FirstOrDefault(q => q.RouteKey == downstreamRoute.Key); if (matchAdvancedAgg != null) { - processing.AddRange(ProcessRouteWithComplexAggregation(matchAdvancedAgg, jObject, context, downstreamRoute)); + processing.AddRange(ProcessRouteWithComplexAggregation(matchAdvancedAgg, jNode, jObject, context, downstreamRoute)); continue; } @@ -163,10 +166,16 @@ private Task MapResponsesAsync(HttpContext context, Route route, HttpContext mai /// Processing a route with aggregation. /// private IEnumerable> ProcessRouteWithComplexAggregation(AggregateRouteConfig matchAdvancedAgg, - JToken jObject, HttpContext httpContext, DownstreamRoute downstreamRoute) + JsonNode jNode, JsonDocument jObject, HttpContext httpContext, DownstreamRoute downstreamRoute) { - var processing = new List>(); - var values = jObject.SelectTokens(matchAdvancedAgg.JsonPath).Select(s => s.ToString()).Distinct(); + var processing = new List>(); + + var tokenPaths = JsonPath.Parse(matchAdvancedAgg.JsonPath); + var values = tokenPaths.Evaluate(jNode) + .Matches + .Select(s => s.Value?.ToString()) + .Distinct(); + foreach (var value in values) { var tPnv = httpContext.Items.TemplatePlaceholderNameAndValues(); diff --git a/src/Ocelot/Ocelot.csproj b/src/Ocelot/Ocelot.csproj index eafb4a446..742f5da90 100644 --- a/src/Ocelot/Ocelot.csproj +++ b/src/Ocelot/Ocelot.csproj @@ -31,6 +31,8 @@ + + NU1701 diff --git a/src/Ocelot/RateLimiting/DistributedCacheRateLimitStorage.cs b/src/Ocelot/RateLimiting/DistributedCacheRateLimitStorage.cs index b7fb79de3..6a6a3057d 100644 --- a/src/Ocelot/RateLimiting/DistributedCacheRateLimitStorage.cs +++ b/src/Ocelot/RateLimiting/DistributedCacheRateLimitStorage.cs @@ -1,5 +1,6 @@ using Microsoft.Extensions.Caching.Distributed; -using Newtonsoft.Json; +using Ocelot.Infrastructure; +using System.Text.Json; namespace Ocelot.RateLimiting; @@ -16,7 +17,7 @@ public class DistributedCacheRateLimitStorage : IRateLimitStorage public DistributedCacheRateLimitStorage(IDistributedCache memoryCache) => _memoryCache = memoryCache; public void Set(string id, RateLimitCounter counter, TimeSpan expirationTime) - => _memoryCache.SetString(id, JsonConvert.SerializeObject(counter), new DistributedCacheEntryOptions().SetAbsoluteExpiration(expirationTime)); + => _memoryCache.SetString(id, JsonSerializer.Serialize(counter, JsonSerializerOptionsExtensions.Web), new DistributedCacheEntryOptions().SetAbsoluteExpiration(expirationTime)); public bool Exists(string id) => !string.IsNullOrEmpty(_memoryCache.GetString(id)); @@ -24,7 +25,7 @@ public void Set(string id, RateLimitCounter counter, TimeSpan expirationTime) { var stored = _memoryCache.GetString(id); return !string.IsNullOrEmpty(stored) - ? JsonConvert.DeserializeObject(stored) + ? JsonSerializer.Deserialize(stored, JsonSerializerOptionsExtensions.Web) : null; } diff --git a/src/Ocelot/RateLimiting/RateLimitCounter.cs b/src/Ocelot/RateLimiting/RateLimitCounter.cs index 2507a0433..850911dfb 100644 --- a/src/Ocelot/RateLimiting/RateLimitCounter.cs +++ b/src/Ocelot/RateLimiting/RateLimitCounter.cs @@ -1,4 +1,6 @@ -using Newtonsoft.Json; + + +using System.Text.Json.Serialization; namespace Ocelot.RateLimiting; diff --git a/src/Ocelot/Requester/MessageInvokerPool.cs b/src/Ocelot/Requester/MessageInvokerPool.cs index 130b4bccb..7e6340838 100644 --- a/src/Ocelot/Requester/MessageInvokerPool.cs +++ b/src/Ocelot/Requester/MessageInvokerPool.cs @@ -76,7 +76,7 @@ private HttpMessageHandler CreateHandler(DownstreamRoute downstreamRoute) UseCookies = downstreamRoute.HttpHandlerOptions.UseCookieContainer, UseProxy = downstreamRoute.HttpHandlerOptions.UseProxy, MaxConnectionsPerServer = downstreamRoute.HttpHandlerOptions.MaxConnectionsPerServer, - PooledConnectionLifetime = downstreamRoute.HttpHandlerOptions.PooledConnectionLifeTime, + PooledConnectionLifetime = downstreamRoute.HttpHandlerOptions.PooledConnectionLifeTime }; if (downstreamRoute.HttpHandlerOptions.UseCookieContainer) diff --git a/test/Ocelot.AcceptanceTests/BearerToken.cs b/test/Ocelot.AcceptanceTests/BearerToken.cs index 48fca2fad..75e56008a 100644 --- a/test/Ocelot.AcceptanceTests/BearerToken.cs +++ b/test/Ocelot.AcceptanceTests/BearerToken.cs @@ -1,15 +1,15 @@ -using Newtonsoft.Json; +using System.Text.Json.Serialization; namespace Ocelot.AcceptanceTests; internal class BearerToken { - [JsonProperty("access_token")] + [JsonPropertyName("access_token")] public string AccessToken { get; set; } - [JsonProperty("expires_in")] + [JsonPropertyName("expires_in")] public int ExpiresIn { get; set; } - [JsonProperty("token_type")] + [JsonPropertyName("token_type")] public string TokenType { get; set; } } diff --git a/test/Ocelot.AcceptanceTests/Caching/CachingTests.cs b/test/Ocelot.AcceptanceTests/Caching/CachingTests.cs index 709ca97c8..dfbe07679 100644 --- a/test/Ocelot.AcceptanceTests/Caching/CachingTests.cs +++ b/test/Ocelot.AcceptanceTests/Caching/CachingTests.cs @@ -1,5 +1,6 @@ using Microsoft.AspNetCore.Http; using Ocelot.Configuration.File; +using Ocelot.Infrastructure; using System.Text; using JsonSerializer = System.Text.Json.JsonSerializer; @@ -298,7 +299,7 @@ private void ThenTheCounterValueShouldBe(int expected) LastName = "Test", }; - var testBody1String = JsonSerializer.Serialize(testBody1); + var testBody1String = JsonSerializer.Serialize(testBody1, JsonSerializerOptionsExtensions.Web); var testBody2 = new TestBody { @@ -308,7 +309,7 @@ private void ThenTheCounterValueShouldBe(int expected) LastName = "Test", }; - var testBody2String = JsonSerializer.Serialize(testBody2); + var testBody2String = JsonSerializer.Serialize(testBody2, JsonSerializerOptionsExtensions.Web); return (testBody1String, testBody2String); } diff --git a/test/Ocelot.AcceptanceTests/Configuration/ConfigurationInConsulTests.cs b/test/Ocelot.AcceptanceTests/Configuration/ConfigurationInConsulTests.cs index e61fdebe3..a595c0bc4 100644 --- a/test/Ocelot.AcceptanceTests/Configuration/ConfigurationInConsulTests.cs +++ b/test/Ocelot.AcceptanceTests/Configuration/ConfigurationInConsulTests.cs @@ -7,7 +7,6 @@ using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; -using Newtonsoft.Json; using Ocelot.AcceptanceTests.Caching; using Ocelot.Cache.CacheManager; using Ocelot.Configuration.File; @@ -15,6 +14,7 @@ using Ocelot.Middleware; using Ocelot.Provider.Consul; using System.Text; +using System.Text.Json; namespace Ocelot.AcceptanceTests.Configuration; @@ -130,7 +130,7 @@ private Task GivenThereIsAFakeConsulServiceDiscoveryProvider(string url, string { if (context.Request.Method.ToLower() == "get" && context.Request.Path.Value == "/v1/kv/InternalConfiguration") { - var json = JsonConvert.SerializeObject(_config); + var json = JsonSerializer.Serialize(_config, JsonSerializerOptionsExtensions.Web); var bytes = Encoding.UTF8.GetBytes(json); @@ -150,9 +150,9 @@ private Task GivenThereIsAFakeConsulServiceDiscoveryProvider(string url, string // var json = reader.ReadToEnd(); var json = await reader.ReadToEndAsync(); - _config = JsonConvert.DeserializeObject(json); + _config = JsonSerializer.Deserialize(json, JsonSerializerOptionsExtensions.Web); - var response = JsonConvert.SerializeObject(true); + var response = JsonSerializer.Serialize(true, JsonSerializerOptionsExtensions.Web); await context.Response.WriteAsync(response); } diff --git a/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulConfigurationInConsulTests.cs b/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulConfigurationInConsulTests.cs index bfe7d345b..5bfa4e923 100644 --- a/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulConfigurationInConsulTests.cs +++ b/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulConfigurationInConsulTests.cs @@ -4,7 +4,6 @@ using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.Configuration; -using Newtonsoft.Json; using Ocelot.AcceptanceTests.RateLimiting; using Ocelot.Cache; using Ocelot.Configuration.File; @@ -12,6 +11,7 @@ using Ocelot.Middleware; using Ocelot.Provider.Consul; using System.Text; +using System.Text.Json; namespace Ocelot.AcceptanceTests.ServiceDiscovery; @@ -386,14 +386,14 @@ private Task GivenThereIsAFakeConsulServiceDiscoveryProvider(string url, string { if (context.Request.Method.ToLower() == "get" && context.Request.Path.Value == "/v1/kv/InternalConfiguration") { - var json = JsonConvert.SerializeObject(_config); + var json = JsonSerializer.Serialize(_config, JsonSerializerOptionsExtensions.Web); var bytes = Encoding.UTF8.GetBytes(json); var base64 = Convert.ToBase64String(bytes); var kvp = new FakeConsulGetResponse(base64); - json = JsonConvert.SerializeObject(new[] { kvp }); + json = JsonSerializer.Serialize(new[] { kvp }, JsonSerializerOptionsExtensions.Web); context.Response.Headers.Append("Content-Type", "application/json"); await context.Response.WriteAsync(json); } @@ -407,9 +407,9 @@ private Task GivenThereIsAFakeConsulServiceDiscoveryProvider(string url, string // var json = reader.ReadToEnd(); var json = await reader.ReadToEndAsync(); - _config = JsonConvert.DeserializeObject(json); + _config = JsonSerializer.Deserialize(json, JsonSerializerOptionsExtensions.Web); - var response = JsonConvert.SerializeObject(true); + var response = JsonSerializer.Serialize(true, JsonSerializerOptionsExtensions.Web); await context.Response.WriteAsync(response); } @@ -421,7 +421,7 @@ private Task GivenThereIsAFakeConsulServiceDiscoveryProvider(string url, string } else if (context.Request.Path.Value == $"/v1/health/service/{serviceName}") { - var json = JsonConvert.SerializeObject(_consulServices); + var json = JsonSerializer.Serialize(_consulServices, JsonSerializerOptionsExtensions.Web); context.Response.Headers.Append("Content-Type", "application/json"); await context.Response.WriteAsync(json); } diff --git a/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulServiceDiscoveryTests.cs b/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulServiceDiscoveryTests.cs index 9a49883b1..42cec8572 100644 --- a/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulServiceDiscoveryTests.cs +++ b/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulServiceDiscoveryTests.cs @@ -2,7 +2,6 @@ using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Net.Http.Headers; -using Newtonsoft.Json; using Ocelot.AcceptanceTests.LoadBalancer; using Ocelot.Configuration; using Ocelot.Configuration.File; @@ -14,6 +13,7 @@ using Ocelot.Provider.Consul.Interfaces; using Ocelot.ServiceDiscovery.Providers; using System.Runtime.CompilerServices; +using System.Text.Json; using System.Text.RegularExpressions; namespace Ocelot.AcceptanceTests.ServiceDiscovery; @@ -537,6 +537,10 @@ public MyConsulServiceBuilder(IHttpContextAccessor contextAccessor, IConsulClien { DownstreamPathTemplate = downstream ?? "/", DownstreamScheme = Uri.UriSchemeHttp, + DownstreamHostAndPorts = new List() + { + new FileHostAndPort("localhost",5000) + }, UpstreamPathTemplate = upstream ?? "/", UpstreamHttpMethod = httpMethods != null ? new(httpMethods) : new() { HttpMethods.Get }, UpstreamHost = upstreamHost, @@ -619,7 +623,7 @@ private void GivenThereIsAFakeConsulServiceDiscoveryProvider(string url) // Use the parsed service name to filter the registered Consul services var serviceName = pathMatch.Groups["serviceName"].Value; var services = _consulServices.Where(x => x.Service.Service == serviceName).ToList(); - var json = JsonConvert.SerializeObject(services); + var json = JsonSerializer.Serialize(services, JsonSerializerOptionsExtensions.Web); //} context.Response.Headers.Append("Content-Type", "application/json"); @@ -631,7 +635,7 @@ private void GivenThereIsAFakeConsulServiceDiscoveryProvider(string url) { //_counterNodes++; int count = Interlocked.Increment(ref _counterNodes); - var json = JsonConvert.SerializeObject(_consulNodes); + var json = JsonSerializer.Serialize(_consulNodes, JsonSerializerOptionsExtensions.Web); context.Response.Headers.Append("Content-Type", "application/json"); await context.Response.WriteAsync(json); } diff --git a/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulWebSocketTests.cs b/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulWebSocketTests.cs index 5be6377d7..0cf55e383 100644 --- a/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulWebSocketTests.cs +++ b/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulWebSocketTests.cs @@ -13,6 +13,7 @@ using Ocelot.WebSockets; using System.Net.WebSockets; using System.Text; +using System.Text.Json; namespace Ocelot.AcceptanceTests.ServiceDiscovery; @@ -174,7 +175,7 @@ private void GivenThereIsAFakeConsulServiceDiscoveryProvider(int port, string se { if (context.Request.Path.Value == $"/v1/health/service/{serviceName}") { - var json = JsonConvert.SerializeObject(_serviceEntries); + var json = JsonSerializer.Serialize(_serviceEntries, JsonSerializerOptionsExtensions.Web); context.Response.Headers.Append("Content-Type", "application/json"); await context.Response.WriteAsync(json); } diff --git a/test/Ocelot.AcceptanceTests/ServiceDiscovery/EurekaServiceDiscoveryTests.cs b/test/Ocelot.AcceptanceTests/ServiceDiscovery/EurekaServiceDiscoveryTests.cs index 5e4b53b9f..729a6a6f6 100644 --- a/test/Ocelot.AcceptanceTests/ServiceDiscovery/EurekaServiceDiscoveryTests.cs +++ b/test/Ocelot.AcceptanceTests/ServiceDiscovery/EurekaServiceDiscoveryTests.cs @@ -1,8 +1,10 @@ using Microsoft.AspNetCore.Http; -using Newtonsoft.Json; using Ocelot.Configuration.File; +using Ocelot.Infrastructure; using Ocelot.LoadBalancer.LoadBalancers; using Steeltoe.Common.Discovery; +using System.Text.Json; +using System.Text.Json.Serialization; namespace Ocelot.AcceptanceTests.ServiceDiscovery; @@ -142,7 +144,7 @@ private void GivenThereIsAFakeEurekaServiceDiscoveryProvider(string url, string }, }; - var json = JsonConvert.SerializeObject(applications); + var json = JsonSerializer.Serialize(applications, JsonSerializerOptionsExtensions.Web); context.Response.Headers.Append("Content-Type", "application/json"); await context.Response.WriteAsync(json); } @@ -192,28 +194,28 @@ public FakeEurekaService(string serviceId, string host, int port, bool isSecure, public IDictionary Metadata { get; } } -public class Port -{ - [JsonProperty("$")] - public int value { get; set; } + public class Port + { + [JsonPropertyName("$")] + public int value { get; set; } - [JsonProperty("@enabled")] - public string enabled { get; set; } -} + [JsonPropertyName("@enabled")] + public string enabled { get; set; } + } -public class SecurePort -{ - [JsonProperty("$")] - public int value { get; set; } + public class SecurePort + { + [JsonPropertyName("$")] + public int value { get; set; } - [JsonProperty("@enabled")] - public string enabled { get; set; } -} + [JsonPropertyName("@enabled")] + public string enabled { get; set; } + } -public class DataCenterInfo -{ - [JsonProperty("@class")] - public string value { get; set; } + public class DataCenterInfo + { + [JsonPropertyName("@class")] + public string value { get; set; } public string name { get; set; } } @@ -233,11 +235,11 @@ public class LeaseInfo public long serviceUpTimestamp { get; set; } } -public class ValueMetadata -{ - [JsonProperty("@class")] - public string value { get; set; } -} + public class ValueMetadata + { + [JsonPropertyName("@class")] + public string value { get; set; } + } public class Instance { diff --git a/test/Ocelot.AcceptanceTests/ServiceDiscovery/KubernetesServiceDiscoveryTests.cs b/test/Ocelot.AcceptanceTests/ServiceDiscovery/KubernetesServiceDiscoveryTests.cs index 7350d5ba7..0adc2eb2f 100644 --- a/test/Ocelot.AcceptanceTests/ServiceDiscovery/KubernetesServiceDiscoveryTests.cs +++ b/test/Ocelot.AcceptanceTests/ServiceDiscovery/KubernetesServiceDiscoveryTests.cs @@ -3,11 +3,11 @@ using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; -using Newtonsoft.Json; using Ocelot.AcceptanceTests.LoadBalancer; using Ocelot.Configuration; using Ocelot.Configuration.File; using Ocelot.DependencyInjection; +using Ocelot.Infrastructure; using Ocelot.LoadBalancer.LoadBalancers; using Ocelot.Logging; using Ocelot.Provider.Kubernetes; @@ -15,6 +15,7 @@ using Ocelot.ServiceDiscovery.Providers; using Ocelot.Values; using System.Runtime.CompilerServices; +using System.Text.Json; namespace Ocelot.AcceptanceTests.ServiceDiscovery; @@ -294,7 +295,7 @@ private void GivenThereIsAFakeKubernetesProvider(EndpointsV1 endpoints, bool isS } endpoints.Metadata.Generation = _k8sServiceGeneration; - json = JsonConvert.SerializeObject(endpoints); + json = JsonSerializer.Serialize(endpoints, JsonSerializerOptionsExtensions.Web); } if (context.Request.Headers.TryGetValue("Authorization", out var values)) diff --git a/test/Ocelot.AcceptanceTests/Steps.cs b/test/Ocelot.AcceptanceTests/Steps.cs index 1de34abb3..3e9c7880a 100644 --- a/test/Ocelot.AcceptanceTests/Steps.cs +++ b/test/Ocelot.AcceptanceTests/Steps.cs @@ -8,7 +8,6 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; -using Newtonsoft.Json; using Ocelot.AcceptanceTests.Caching; using Ocelot.AcceptanceTests.Properties; using Ocelot.Cache.CacheManager; @@ -17,6 +16,8 @@ using Ocelot.Configuration.File; using Ocelot.Configuration.Repository; using Ocelot.DependencyInjection; +using Ocelot.Infrastructure; +using Ocelot.LoadBalancer.LoadBalancers; using Ocelot.Logging; using Ocelot.Middleware; using Ocelot.Provider.Eureka; @@ -28,6 +29,7 @@ using System.IO.Compression; using System.Net.Http.Headers; using System.Text; +using System.Text.Json; using static Ocelot.AcceptanceTests.HttpDelegatingHandlersTests; using ConfigurationBuilder = Microsoft.Extensions.Configuration.ConfigurationBuilder; using CookieHeaderValue = Microsoft.Net.Http.Headers.CookieHeaderValue; @@ -58,7 +60,7 @@ public Steps() : base() { _random = new Random(); _testId = Guid.NewGuid(); - _ocelotConfigFileName = $"{_testId:N}-{ConfigurationBuilderExtensions.PrimaryConfigFile}"; + _ocelotConfigFileName = $"{_testId:N}-{ConfigurationBuilderExtensions.PrimaryConfigFile}"; Files = new() { _ocelotConfigFileName }; Folders = new(); } @@ -74,8 +76,8 @@ public Steps() : base() protected static FileConfiguration GivenConfiguration(params FileRoute[] routes) => new() { Routes = new(routes), - }; - + }; + protected static FileRoute GivenDefaultRoute(int port) => new() { DownstreamPathTemplate = "/", @@ -108,7 +110,7 @@ public async Task ThenConfigShouldBeWithTimeout(FileConfiguration fileConfig, in }); result.ShouldBe(true); } - + /// /// TODO Move to . See references. /// @@ -147,9 +149,9 @@ public async Task StartFakeOcelotWithWebSockets() _ocelotHost = _ocelotBuilder.Build(); await _ocelotHost.StartAsync(); } - + public void GivenThereIsAConfiguration(FileConfiguration fileConfiguration) - => GivenThereIsAConfiguration(fileConfiguration, _ocelotConfigFileName); + => GivenThereIsAConfiguration(fileConfiguration, _ocelotConfigFileName); public void GivenThereIsAConfiguration(FileConfiguration from, string toFile) { var json = SerializeJson(from, ref toFile); @@ -162,10 +164,10 @@ public Task GivenThereIsAConfigurationAsync(FileConfiguration from, string toFil } protected string SerializeJson(FileConfiguration from, ref string toFile) { - toFile ??= _ocelotConfigFileName; - Files.Add(toFile); // register for disposing - return JsonConvert.SerializeObject(from, Formatting.Indented); - } + toFile ??= _ocelotConfigFileName; + Files.Add(toFile); // register for disposing + return JsonSerializer.Serialize(from, JsonSerializerOptionsExtensions.WebWriteIndented); + } protected virtual void DeleteFiles() { @@ -199,12 +201,12 @@ protected virtual void DeleteFolders() f.Delete(true); } } - catch (Exception e) - { - Console.WriteLine(e); - } + catch (Exception e) + { + Console.WriteLine(e); + } } - } + } public void ThenTheResponseBodyHeaderIs(string key, string value) { @@ -477,20 +479,20 @@ public async Task WhenIGetUrlOnTheApiGatewayWithCookie(string url, string cookie => _response = await WhenIGetUrlOnTheApiGateway(url, cookie, value); public async Task WhenIGetUrlOnTheApiGatewayWithCookie(string url, CookieHeaderValue cookie) => _response = await WhenIGetUrlOnTheApiGateway(url, cookie); - + public Task WhenIGetUrlOnTheApiGateway(string url, string cookie, string value) { var header = new CookieHeaderValue(cookie, value); return WhenIGetUrlOnTheApiGateway(url, header); - } - + } + public Task WhenIGetUrlOnTheApiGateway(string url, CookieHeaderValue cookie) - { + { var requestMessage = new HttpRequestMessage(HttpMethod.Get, url); requestMessage.Headers.Add("Cookie", cookie.ToString()); return _ocelotClient.SendAsync(requestMessage); - } - + } + // END of Cookies helpers /// @@ -530,7 +532,7 @@ public void ThenTheResponseHeaderIs(string key, string value) public void ThenTheReasonPhraseIs(string expected) { _response.ReasonPhrase.ShouldBe(expected); - } + } public void GivenOcelotIsRunningWithServices(Action configureServices) => GivenOcelotIsRunningWithServices(configureServices, null); @@ -617,7 +619,7 @@ internal async Task GivenIHaveATokenWithForm(string url, IEnumerabl var response = await httpClient.PostAsync(tokenUrl, content); var responseContent = await response.Content.ReadAsStringAsync(); response.EnsureSuccessStatusCode(); - _token = JsonConvert.DeserializeObject(responseContent); + _token = JsonSerializer.Deserialize(responseContent, JsonSerializerOptionsExtensions.Web); return _token; } @@ -721,18 +723,18 @@ public void GivenIAddAHeader(string key, string value) { _ocelotClient.DefaultRequestHeaders.TryAddWithoutValidation(key, value); } - + public static void WhenIDoActionMultipleTimes(int times, Action action) - { + { for (int i = 0; i < times; i++) action?.Invoke(i); - } - + } + public static async Task WhenIDoActionMultipleTimes(int times, Func action) - { + { for (int i = 0; i < times; i++) await action.Invoke(i); - } + } public async Task WhenIGetUrlOnTheApiGateway(string url, string requestId) { @@ -757,7 +759,7 @@ public void GivenThePostHasContentType(string postContent) public void GivenThePostHasGzipContent(object input) { - var json = JsonConvert.SerializeObject(input); + var json = JsonSerializer.Serialize(input, JsonSerializerOptionsExtensions.Web); var jsonBytes = Encoding.UTF8.GetBytes(json); var ms = new MemoryStream(); using (var gzip = new GZipStream(ms, CompressionMode.Compress, true)) @@ -772,12 +774,12 @@ public void GivenThePostHasGzipContent(object input) _postContent = content; } - public void ThenTheResponseBodyShouldBe(string expectedBody) + public void ThenTheResponseBodyShouldBe(string expectedBody) => _response.Content.ReadAsStringAsync().GetAwaiter().GetResult().ShouldBe(expectedBody); public void ThenTheResponseBodyShouldBe(string expectedBody, string customMessage) => _response.Content.ReadAsStringAsync().GetAwaiter().GetResult().ShouldBe(expectedBody, customMessage); - public void ThenTheContentLengthIs(int expected) + public void ThenTheContentLengthIs(int expected) => _response.Content.Headers.ContentLength.ShouldBe(expected); public void ThenTheStatusCodeShouldBe(HttpStatusCode expected) @@ -785,10 +787,10 @@ public void ThenTheStatusCodeShouldBe(HttpStatusCode expected) public void ThenTheStatusCodeShouldBe(int expected) => ((int)_response.StatusCode).ShouldBe(expected); - public void ThenTheRequestIdIsReturned() + public void ThenTheRequestIdIsReturned() => _response.Headers.GetValues(RequestIdKey).First().ShouldNotBeNullOrEmpty(); - public void ThenTheRequestIdIsReturned(string expected) + public void ThenTheRequestIdIsReturned(string expected) => _response.Headers.GetValues(RequestIdKey).First().ShouldBe(expected); public void WhenIMakeLotsOfDifferentRequestsToTheApiGateway() @@ -970,7 +972,7 @@ protected virtual void Dispose(bool disposing) } if (disposing) - { + { _ocelotClient?.Dispose(); _ocelotServer?.Dispose(); _ocelotHost?.Dispose(); diff --git a/test/Ocelot.AcceptanceTests/TwoDownstreamServicesTests.cs b/test/Ocelot.AcceptanceTests/TwoDownstreamServicesTests.cs index 78ba7d22d..7bdb5d081 100644 --- a/test/Ocelot.AcceptanceTests/TwoDownstreamServicesTests.cs +++ b/test/Ocelot.AcceptanceTests/TwoDownstreamServicesTests.cs @@ -1,7 +1,8 @@ using Consul; using Microsoft.AspNetCore.Http; -using Newtonsoft.Json; using Ocelot.Configuration.File; +using Ocelot.Infrastructure; +using System.Text.Json; namespace Ocelot.AcceptanceTests; @@ -96,7 +97,7 @@ private void GivenThereIsAFakeConsulServiceDiscoveryProvider(string url) { if (context.Request.Path.Value == "/v1/health/service/product") { - var json = JsonConvert.SerializeObject(_serviceEntries); + var json = JsonSerializer.Serialize(_serviceEntries, JsonSerializerOptionsExtensions.Web); context.Response.Headers.Append("Content-Type", "application/json"); await context.Response.WriteAsync(json); } diff --git a/test/Ocelot.Benchmarks/AllTheThingsBenchmarks.cs b/test/Ocelot.Benchmarks/AllTheThingsBenchmarks.cs index fec5d9e5d..84179b264 100644 --- a/test/Ocelot.Benchmarks/AllTheThingsBenchmarks.cs +++ b/test/Ocelot.Benchmarks/AllTheThingsBenchmarks.cs @@ -3,10 +3,11 @@ using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; -using Newtonsoft.Json; using Ocelot.Configuration.File; using Ocelot.DependencyInjection; +using Ocelot.Infrastructure; using Ocelot.Middleware; +using System.Text.Json; namespace Ocelot.Benchmarks; @@ -112,7 +113,7 @@ public static void GivenThereIsAConfiguration(FileConfiguration fileConfiguratio { var configurationPath = Path.Combine(AppContext.BaseDirectory, "ocelot.json"); - var jsonConfiguration = JsonConvert.SerializeObject(fileConfiguration); + var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsExtensions.Web); if (File.Exists(configurationPath)) { diff --git a/test/Ocelot.Benchmarks/MsLoggerBenchmarks.cs b/test/Ocelot.Benchmarks/MsLoggerBenchmarks.cs index b8b53ff1b..174edbbe9 100644 --- a/test/Ocelot.Benchmarks/MsLoggerBenchmarks.cs +++ b/test/Ocelot.Benchmarks/MsLoggerBenchmarks.cs @@ -5,11 +5,12 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; -using Newtonsoft.Json; using Ocelot.Configuration.File; using Ocelot.DependencyInjection; +using Ocelot.Infrastructure; using Ocelot.Logging; using Ocelot.Middleware; +using System.Text.Json; namespace Ocelot.Benchmarks; @@ -162,7 +163,7 @@ public static void GivenThereIsAConfiguration(FileConfiguration fileConfiguratio { var configurationPath = Path.Combine(AppContext.BaseDirectory, "ocelot.json"); - var jsonConfiguration = JsonConvert.SerializeObject(fileConfiguration); + var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsExtensions.Web); if (File.Exists(configurationPath)) { diff --git a/test/Ocelot.Benchmarks/PayloadBenchmarks.cs b/test/Ocelot.Benchmarks/PayloadBenchmarks.cs index aa967d16f..2acf8d2be 100644 --- a/test/Ocelot.Benchmarks/PayloadBenchmarks.cs +++ b/test/Ocelot.Benchmarks/PayloadBenchmarks.cs @@ -4,14 +4,15 @@ using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; -using Newtonsoft.Json; using Ocelot.Configuration.File; using Ocelot.DependencyInjection; +using Ocelot.Infrastructure; using Ocelot.Middleware; using System.Diagnostics; using System.Net.Http.Headers; using System.Reflection; using System.Text; +using System.Text.Json; namespace Ocelot.Benchmarks; @@ -112,7 +113,7 @@ private static string GetBaseDirectory() private static object[] GeneratePayload(int size, string directory, string fileName, bool isJson) { var filePath = Path.Combine(directory, fileName); - var generateDummy = isJson ? (Func) GenerateDummyJsonFile : GenerateDummyDatFile; + var generateDummy = isJson ? (Func)GenerateDummyJsonFile : GenerateDummyDatFile; return new object[] { generateDummy(size, filePath), @@ -220,7 +221,7 @@ private void GivenOcelotIsRunning(string url) public static void GivenThereIsAConfiguration(FileConfiguration fileConfiguration) { var configurationPath = Path.Combine(AppContext.BaseDirectory, ConfigurationBuilderExtensions.PrimaryConfigFile); - var jsonConfiguration = JsonConvert.SerializeObject(fileConfiguration); + var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsExtensions.Web); if (File.Exists(configurationPath)) { diff --git a/test/Ocelot.Benchmarks/ResponseBenchmarks.cs b/test/Ocelot.Benchmarks/ResponseBenchmarks.cs index 53788b140..205d1c564 100644 --- a/test/Ocelot.Benchmarks/ResponseBenchmarks.cs +++ b/test/Ocelot.Benchmarks/ResponseBenchmarks.cs @@ -4,15 +4,15 @@ using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; -using Newtonsoft.Json; using Ocelot.Configuration.File; using Ocelot.DependencyInjection; +using Ocelot.Infrastructure; using Ocelot.Middleware; using System.Diagnostics; using System.Net.Http.Headers; using System.Reflection; using System.Text; -using Ocelot.Responses; +using System.Text.Json; namespace Ocelot.Benchmarks; @@ -222,7 +222,7 @@ private void GivenOcelotIsRunning(string url) public static void GivenThereIsAConfiguration(FileConfiguration fileConfiguration) { var configurationPath = Path.Combine(AppContext.BaseDirectory, ConfigurationBuilderExtensions.PrimaryConfigFile); - var jsonConfiguration = JsonConvert.SerializeObject(fileConfiguration); + var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsExtensions.Web); if (File.Exists(configurationPath)) { diff --git a/test/Ocelot.Benchmarks/SerilogBenchmarks.cs b/test/Ocelot.Benchmarks/SerilogBenchmarks.cs index cd2adcb98..15218b19b 100644 --- a/test/Ocelot.Benchmarks/SerilogBenchmarks.cs +++ b/test/Ocelot.Benchmarks/SerilogBenchmarks.cs @@ -5,13 +5,14 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; -using Newtonsoft.Json; using Ocelot.Configuration.File; using Ocelot.DependencyInjection; +using Ocelot.Infrastructure; using Ocelot.Logging; using Ocelot.Middleware; using Serilog; using Serilog.Core; +using System.Text.Json; namespace Ocelot.Benchmarks; @@ -193,7 +194,7 @@ public static void GivenThereIsAConfiguration(FileConfiguration fileConfiguratio { var configurationPath = Path.Combine(AppContext.BaseDirectory, "ocelot.json"); - var jsonConfiguration = JsonConvert.SerializeObject(fileConfiguration); + var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsExtensions.Web); if (File.Exists(configurationPath)) { diff --git a/test/Ocelot.IntegrationTests/AdministrationTests.cs b/test/Ocelot.IntegrationTests/AdministrationTests.cs index b0e23657e..7f7b84e54 100644 --- a/test/Ocelot.IntegrationTests/AdministrationTests.cs +++ b/test/Ocelot.IntegrationTests/AdministrationTests.cs @@ -8,16 +8,17 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.IdentityModel.Tokens; -using Newtonsoft.Json; using Ocelot.Administration; using Ocelot.Cache; using Ocelot.Configuration.ChangeTracking; using Ocelot.Configuration.File; using Ocelot.DependencyInjection; +using Ocelot.Infrastructure; using Ocelot.Middleware; using System.Net; using System.Net.Http.Headers; using System.Reflection; +using System.Text.Json; namespace Ocelot.IntegrationTests; @@ -342,12 +343,12 @@ private static void ThenTheConfigurationIsSavedCorrectly(FileConfiguration expec { var ocelotJsonPath = $"{AppContext.BaseDirectory}ocelot.json"; var resultText = File.ReadAllText(ocelotJsonPath); - var expectedText = JsonConvert.SerializeObject(expected, Formatting.Indented); + var expectedText = JsonSerializer.Serialize(expected, JsonSerializerOptionsExtensions.WebWriteIndented); resultText.ShouldBe(expectedText); var environmentSpecificPath = $"{AppContext.BaseDirectory}/ocelot.Production.json"; resultText = File.ReadAllText(environmentSpecificPath); - expectedText = JsonConvert.SerializeObject(expected, Formatting.Indented); + expectedText = JsonSerializer.Serialize(expected, JsonSerializerOptionsExtensions.WebWriteIndented); resultText.ShouldBe(expectedText); } @@ -523,7 +524,7 @@ private async Task GivenIHaveAToken(string url) var response = await httpClient.PostAsync($"{url}/connect/token", content); var responseContent = await response.Content.ReadAsStringAsync(); response.EnsureSuccessStatusCode(); - _token = JsonConvert.DeserializeObject(responseContent); + _token = JsonSerializer.Deserialize(responseContent, JsonSerializerOptionsExtensions.Web); } private async Task GivenThereIsAnIdentityServerOn(string url, string apiName) @@ -640,7 +641,7 @@ private async Task WhenIGetUrlOnTheSecondOcelot(string url) private async Task WhenIPostOnTheApiGateway(string url, FileConfiguration updatedConfiguration) { - var json = JsonConvert.SerializeObject(updatedConfiguration); + var json = JsonSerializer.Serialize(updatedConfiguration, JsonSerializerOptionsExtensions.Web); var content = new StringContent(json); content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); _response = await _httpClient.PostAsync(url, content); @@ -654,7 +655,7 @@ private async Task ThenTheResponseBodyShouldBe(string expected) private async Task ThenTheResponseShouldBe(FileConfiguration expecteds) { - var response = JsonConvert.DeserializeObject(await _response.Content.ReadAsStringAsync()); + var response = JsonSerializer.Deserialize(await _response.Content.ReadAsStringAsync(), JsonSerializerOptionsExtensions.Web); response.GlobalConfiguration.RequestIdKey.ShouldBe(expecteds.GlobalConfiguration.RequestIdKey); response.GlobalConfiguration.ServiceDiscoveryProvider.Scheme.ShouldBe(expecteds.GlobalConfiguration.ServiceDiscoveryProvider.Scheme); @@ -698,7 +699,7 @@ private async Task GivenIHaveAnOcelotToken(string adminPath) var response = await _httpClient.PostAsync(tokenUrl, content); var responseContent = await response.Content.ReadAsStringAsync(); response.EnsureSuccessStatusCode(); - _token = JsonConvert.DeserializeObject(responseContent); + _token = JsonSerializer.Deserialize(responseContent, JsonSerializerOptionsExtensions.Web); var configPath = $"{adminPath}/.well-known/openid-configuration"; response = await _httpClient.GetAsync(configPath); response.EnsureSuccessStatusCode(); @@ -825,7 +826,7 @@ private static async Task GivenThereIsAConfiguration(FileConfiguration fileConfi { var configurationPath = $"{Directory.GetCurrentDirectory()}/ocelot.json"; - var jsonConfiguration = JsonConvert.SerializeObject(fileConfiguration); + var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsExtensions.Web); if (File.Exists(configurationPath)) { diff --git a/test/Ocelot.IntegrationTests/BearerToken.cs b/test/Ocelot.IntegrationTests/BearerToken.cs index ffc3688eb..7a4d7c712 100644 --- a/test/Ocelot.IntegrationTests/BearerToken.cs +++ b/test/Ocelot.IntegrationTests/BearerToken.cs @@ -1,15 +1,14 @@ -using Newtonsoft.Json; namespace Ocelot.IntegrationTests; internal class BearerToken { - [JsonProperty("access_token")] + [JsonPropertyName("access_token")] public string AccessToken { get; set; } - [JsonProperty("expires_in")] + [JsonPropertyName("expires_in")] public int ExpiresIn { get; set; } - [JsonProperty("token_type")] + [JsonPropertyName("token_type")] public string TokenType { get; set; } } diff --git a/test/Ocelot.IntegrationTests/CacheManagerTests.cs b/test/Ocelot.IntegrationTests/CacheManagerTests.cs index 9682de44a..518e9141e 100644 --- a/test/Ocelot.IntegrationTests/CacheManagerTests.cs +++ b/test/Ocelot.IntegrationTests/CacheManagerTests.cs @@ -3,14 +3,15 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; -using Newtonsoft.Json; using Ocelot.Administration; using Ocelot.Cache.CacheManager; using Ocelot.Configuration.File; using Ocelot.DependencyInjection; +using Ocelot.Infrastructure; using Ocelot.Middleware; using System.Net; using System.Net.Http.Headers; +using System.Text.Json; namespace Ocelot.IntegrationTests; @@ -111,7 +112,7 @@ private async Task GivenIHaveAnOcelotToken(string adminPath) var response = await _httpClient.PostAsync(tokenUrl, content); var responseContent = await response.Content.ReadAsStringAsync(); response.EnsureSuccessStatusCode(); - _token = JsonConvert.DeserializeObject(responseContent); + _token = JsonSerializer.Deserialize(responseContent, JsonSerializerOptionsExtensions.Web); var configPath = $"{adminPath}/.well-known/openid-configuration"; response = await _httpClient.GetAsync(configPath); response.EnsureSuccessStatusCode(); @@ -161,7 +162,7 @@ private static void GivenThereIsAConfiguration(FileConfiguration fileConfigurati // TODO: Turn method as async var configurationPath = $"{Directory.GetCurrentDirectory()}/ocelot.json"; - var jsonConfiguration = JsonConvert.SerializeObject(fileConfiguration); + var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsExtensions.Web); if (File.Exists(configurationPath)) { diff --git a/test/Ocelot.IntegrationTests/HeaderTests.cs b/test/Ocelot.IntegrationTests/HeaderTests.cs index 04ea60323..1972f3393 100644 --- a/test/Ocelot.IntegrationTests/HeaderTests.cs +++ b/test/Ocelot.IntegrationTests/HeaderTests.cs @@ -2,11 +2,12 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; -using Newtonsoft.Json; using Ocelot.Configuration.File; using Ocelot.DependencyInjection; +using Ocelot.Infrastructure; using Ocelot.Middleware; using System.Net; +using System.Text.Json; [assembly: CollectionBehavior(DisableTestParallelization = true)] @@ -122,7 +123,7 @@ private static void GivenThereIsAConfiguration(FileConfiguration fileConfigurati { var configurationPath = $"{Directory.GetCurrentDirectory()}/ocelot.json"; - var jsonConfiguration = JsonConvert.SerializeObject(fileConfiguration); + var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsExtensions.Web); if (File.Exists(configurationPath)) { diff --git a/test/Ocelot.IntegrationTests/ThreadSafeHeadersTests.cs b/test/Ocelot.IntegrationTests/ThreadSafeHeadersTests.cs index bce5761f8..4f9db3b90 100644 --- a/test/Ocelot.IntegrationTests/ThreadSafeHeadersTests.cs +++ b/test/Ocelot.IntegrationTests/ThreadSafeHeadersTests.cs @@ -2,11 +2,12 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; -using Newtonsoft.Json; using Ocelot.Configuration.File; using Ocelot.DependencyInjection; +using Ocelot.Infrastructure; using Ocelot.Middleware; using System.Collections.Concurrent; +using System.Text.Json; namespace Ocelot.IntegrationTests; @@ -118,7 +119,7 @@ private static void GivenThereIsAConfiguration(FileConfiguration fileConfigurati { var configurationPath = $"{Directory.GetCurrentDirectory()}/ocelot.json"; - var jsonConfiguration = JsonConvert.SerializeObject(fileConfiguration); + var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsExtensions.Web); if (File.Exists(configurationPath)) { diff --git a/test/Ocelot.IntegrationTests/ocelot.json b/test/Ocelot.IntegrationTests/ocelot.json index 39b71c1bb..fdfcbaeef 100644 --- a/test/Ocelot.IntegrationTests/ocelot.json +++ b/test/Ocelot.IntegrationTests/ocelot.json @@ -33,7 +33,7 @@ "ClientWhitelist": [], "EnableRateLimiting": false, "Period": null, - "PeriodTimespan": 0.0, + "PeriodTimespan": 0, "Limit": 0 } } diff --git a/test/Ocelot.ManualTest/CustomOcelotMiddleware.cs b/test/Ocelot.ManualTest/CustomOcelotMiddleware.cs index f3d251887..cf5f70163 100644 --- a/test/Ocelot.ManualTest/CustomOcelotMiddleware.cs +++ b/test/Ocelot.ManualTest/CustomOcelotMiddleware.cs @@ -1,4 +1,5 @@ -using Ocelot.Logging; +using Ocelot.Infrastructure; +using Ocelot.Logging; using Ocelot.Middleware; using System.Text.Json; using System.Threading.Tasks; @@ -16,7 +17,7 @@ public static Task Invoke(HttpContext context, Func next) { logger.LogInformation(() => { - var metadataInJson = JsonSerializer.Serialize(metadata); + var metadataInJson = JsonSerializer.Serialize(metadata, JsonSerializerOptionsExtensions.Web); var message = $"My custom middleware found some metadata: {metadataInJson}"; return message; }); diff --git a/test/Ocelot.UnitTests/Configuration/DiskFileConfigurationRepositoryTests.cs b/test/Ocelot.UnitTests/Configuration/DiskFileConfigurationRepositoryTests.cs index 5a37ed05e..c95a391fe 100644 --- a/test/Ocelot.UnitTests/Configuration/DiskFileConfigurationRepositoryTests.cs +++ b/test/Ocelot.UnitTests/Configuration/DiskFileConfigurationRepositoryTests.cs @@ -1,10 +1,11 @@ using Microsoft.AspNetCore.Hosting; -using Newtonsoft.Json; using Ocelot.Configuration.ChangeTracking; using Ocelot.Configuration.File; using Ocelot.Configuration.Repository; using Ocelot.DependencyInjection; +using Ocelot.Infrastructure; using System.Runtime.CompilerServices; +using System.Text.Json; namespace Ocelot.UnitTests.Configuration; @@ -156,14 +157,14 @@ private void ThenTheConfigurationIsStoredAs(FileConfiguration expecteds) private static void ThenTheOcelotJsonIsStoredAs(FileInfo ocelotJson, FileConfiguration expecteds) { var actual = File.ReadAllText(ocelotJson.FullName); - var expectedText = JsonConvert.SerializeObject(expecteds, Formatting.Indented); + var expectedText = JsonSerializer.Serialize(expecteds, JsonSerializerOptionsExtensions.WebWriteIndented); actual.ShouldBe(expectedText); } private void GivenTheConfigurationIs(FileConfiguration fileConfiguration, [CallerMemberName] string environmentName = null) { - var environmentSpecificPath = Path.Combine(TestID, string.Format(ConfigurationBuilderExtensions.EnvironmentConfigFile, environmentName)); - var jsonConfiguration = JsonConvert.SerializeObject(fileConfiguration, Formatting.Indented); + var environmentSpecificPath = Path.Combine(TestID, string.Format(ConfigurationBuilderExtensions.EnvironmentConfigFile, environmentName)); + var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsExtensions.WebWriteIndented); var environmentSpecific = new FileInfo(environmentSpecificPath); if (environmentSpecific.Exists) { @@ -178,7 +179,7 @@ private void ThenTheConfigurationJsonIsIndented(FileConfiguration expecteds, [Ca { var environmentSpecific = Path.Combine(TestID, string.Format(ConfigurationBuilderExtensions.EnvironmentConfigFile, environmentName)); var actual = File.ReadAllText(environmentSpecific); - var expectedText = JsonConvert.SerializeObject(expecteds, Formatting.Indented); + var expectedText = JsonSerializer.Serialize(expecteds, JsonSerializerOptionsExtensions.WebWriteIndented); actual.ShouldBe(expectedText); _files.Add(environmentSpecific); } diff --git a/test/Ocelot.UnitTests/Consul/ConsulFileConfigurationRepositoryTests.cs b/test/Ocelot.UnitTests/Consul/ConsulFileConfigurationRepositoryTests.cs index 474c5c1ac..038c8e22e 100644 --- a/test/Ocelot.UnitTests/Consul/ConsulFileConfigurationRepositoryTests.cs +++ b/test/Ocelot.UnitTests/Consul/ConsulFileConfigurationRepositoryTests.cs @@ -1,13 +1,14 @@ using Consul; using Microsoft.Extensions.Options; -using Newtonsoft.Json; using Ocelot.Cache; using Ocelot.Configuration.File; +using Ocelot.Infrastructure; using Ocelot.Logging; using Ocelot.Provider.Consul; using Ocelot.Provider.Consul.Interfaces; using Ocelot.Responses; using System.Text; +using System.Text.Json; namespace Ocelot.UnitTests.Consul; @@ -141,8 +142,8 @@ private void GivenTheConfigKeyComesFromFileConfig(string key) private void ThenTheConfigurationIs(FileConfiguration config) { - var expected = JsonConvert.SerializeObject(config, Formatting.Indented); - var result = JsonConvert.SerializeObject(_getResult.Data, Formatting.Indented); + var expected = JsonSerializer.Serialize(config, JsonSerializerOptionsExtensions.WebWriteIndented); + var result = JsonSerializer.Serialize(_getResult.Data, JsonSerializerOptionsExtensions.WebWriteIndented); result.ShouldBe(expected); } @@ -169,7 +170,7 @@ private void GivenFetchFromConsulReturnsNull() private void GivenFetchFromConsulSucceeds() { - var json = JsonConvert.SerializeObject(_fileConfiguration, Formatting.Indented); + var json = JsonSerializer.Serialize(_fileConfiguration, JsonSerializerOptionsExtensions.WebWriteIndented); var bytes = Encoding.UTF8.GetBytes(json); var kvp = new KVPair("OcelotConfiguration") { @@ -185,7 +186,7 @@ private void GivenFetchFromConsulSucceeds() private void ThenTheConfigurationIsStoredAs(FileConfiguration config) { - var json = JsonConvert.SerializeObject(config, Formatting.Indented); + var json = JsonSerializer.Serialize(config, JsonSerializerOptionsExtensions.WebWriteIndented); var bytes = Encoding.UTF8.GetBytes(json); _kvEndpoint.Verify(x => x.Put(It.Is(k => k.Value.SequenceEqual(bytes)), It.IsAny()), Times.Once); } diff --git a/test/Ocelot.UnitTests/Consul/ConsulTests.cs b/test/Ocelot.UnitTests/Consul/ConsulTests.cs index 13f39129a..97006ef3a 100644 --- a/test/Ocelot.UnitTests/Consul/ConsulTests.cs +++ b/test/Ocelot.UnitTests/Consul/ConsulTests.cs @@ -2,11 +2,12 @@ using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; -using Newtonsoft.Json; +using Ocelot.Infrastructure; using Ocelot.Logging; using Ocelot.Provider.Consul; using Ocelot.Provider.Consul.Interfaces; using System.Runtime.CompilerServices; +using System.Text.Json; using ConsulProvider = Ocelot.Provider.Consul.Consul; namespace Ocelot.UnitTests.Consul; @@ -204,7 +205,7 @@ private void GivenThereIsAFakeConsulServiceDiscoveryProvider([CallerMemberName] _receivedToken = values.First(); } - var json = JsonConvert.SerializeObject(_consulServiceEntries); + var json = JsonSerializer.Serialize(_consulServiceEntries, JsonSerializerOptionsExtensions.Web); context.Response.Headers.Append("Content-Type", "application/json"); await context.Response.WriteAsync(json); } diff --git a/test/Ocelot.UnitTests/DependencyInjection/ConfigurationBuilderExtensionsTests.cs b/test/Ocelot.UnitTests/DependencyInjection/ConfigurationBuilderExtensionsTests.cs index 3002048e7..389487bcb 100644 --- a/test/Ocelot.UnitTests/DependencyInjection/ConfigurationBuilderExtensionsTests.cs +++ b/test/Ocelot.UnitTests/DependencyInjection/ConfigurationBuilderExtensionsTests.cs @@ -1,10 +1,11 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.VisualStudio.TestPlatform.ObjectModel; -using Newtonsoft.Json; using Ocelot.Configuration.File; using Ocelot.DependencyInjection; +using Ocelot.Infrastructure; using System.Runtime.CompilerServices; +using System.Text.Json; namespace Ocelot.UnitTests.DependencyInjection; @@ -187,8 +188,8 @@ private void GivenMultipleConfigurationFiles(string folder, bool withEnvironment foreach (var part in configParts) { - var filename = Path.Combine(folder, string.Format(ConfigurationBuilderExtensions.EnvironmentConfigFile, part.Key)); - File.WriteAllText(filename, JsonConvert.SerializeObject(part.Value, Formatting.Indented)); + var filename = Path.Combine(folder, string.Format(ConfigurationBuilderExtensions.EnvironmentConfigFile, part.Key)); + File.WriteAllText(filename, JsonSerializer.Serialize(part.Value, JsonSerializerOptionsExtensions.WebWriteIndented)); _files.Add(filename); } } diff --git a/test/Ocelot.UnitTests/DependencyInjection/OcelotBuilderTests.cs b/test/Ocelot.UnitTests/DependencyInjection/OcelotBuilderTests.cs index 736282208..5d6321589 100644 --- a/test/Ocelot.UnitTests/DependencyInjection/OcelotBuilderTests.cs +++ b/test/Ocelot.UnitTests/DependencyInjection/OcelotBuilderTests.cs @@ -6,8 +6,6 @@ using Microsoft.AspNetCore.Mvc.ApplicationModels; using Microsoft.AspNetCore.Mvc.ApplicationParts; using Microsoft.AspNetCore.Mvc.Controllers; -using Microsoft.AspNetCore.Mvc.Infrastructure; -using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; @@ -324,17 +322,7 @@ private void CstorShouldUseDefaultBuilderToInitMvcCoreBuilder() .ShouldNotBeNull() .GetType().Name.ShouldBe("AuthorizationApplicationModelProvider"); - // .AddNewtonsoftJson() - _serviceProvider.GetServices>() - .FirstOrDefault(s => s.GetType().Name == "NewtonsoftJsonMvcOptionsSetup") - .ShouldNotBeNull(); - _serviceProvider.GetService>() - .ShouldNotBeNull() - .GetType().Name.ShouldBe("NewtonsoftJsonResultExecutor"); - _serviceProvider.GetService() - .ShouldNotBeNull() - .GetType().Name.ShouldBe("NewtonsoftJsonHelper"); - } + } [Fact] public void Should_use_custom_mvc_builder_no_configuration() diff --git a/test/Ocelot.UnitTests/Kubernetes/KubeTests.cs b/test/Ocelot.UnitTests/Kubernetes/KubeTests.cs index d6c13f60d..56b49f5a8 100644 --- a/test/Ocelot.UnitTests/Kubernetes/KubeTests.cs +++ b/test/Ocelot.UnitTests/Kubernetes/KubeTests.cs @@ -3,13 +3,14 @@ using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; -using Newtonsoft.Json; +using Ocelot.Infrastructure; using Ocelot.Logging; using Ocelot.Provider.Kubernetes; using Ocelot.Provider.Kubernetes.Interfaces; using Ocelot.Testing; using Ocelot.Values; using System.Runtime.CompilerServices; +using System.Text.Json; namespace Ocelot.UnitTests.Kubernetes; @@ -160,7 +161,7 @@ Task ProcessKubernetesRequest(HttpContext context) token = values.First(); } - var json = JsonConvert.SerializeObject(endpointEntries); + var json = JsonSerializer.Serialize(_endpointEntries, JsonSerializerOptionsExtensions.Web); context.Response.Headers.Append("Content-Type", "application/json"); return context.Response.WriteAsync(json); } diff --git a/test/Ocelot.UnitTests/Requester/MessageInvokerPoolTests.cs b/test/Ocelot.UnitTests/Requester/MessageInvokerPoolTests.cs index 2e8ed678b..30bf5cd50 100644 --- a/test/Ocelot.UnitTests/Requester/MessageInvokerPoolTests.cs +++ b/test/Ocelot.UnitTests/Requester/MessageInvokerPoolTests.cs @@ -226,7 +226,7 @@ private void GivenARequestWithAUrlAndMethod(DownstreamRoute downstream, string u { _context.Items.UpsertDownstreamRoute(downstream); _context.Items.UpsertDownstreamRequest(new DownstreamRequest(new HttpRequestMessage - { RequestUri = new Uri(url), Method = method })); + { RequestUri = new Uri(url), Method = method })); } private async Task WhenICallTheClient(string url) From 635439b039bc0cc7e6ddc17dd7d3772128b8429f Mon Sep 17 00:00:00 2001 From: Mohsen Rajabi Date: Fri, 19 Jul 2024 10:46:24 +0330 Subject: [PATCH 02/26] feat: add system text json config --- src/Ocelot/DependencyInjection/OcelotBuilder.cs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/src/Ocelot/DependencyInjection/OcelotBuilder.cs b/src/Ocelot/DependencyInjection/OcelotBuilder.cs index 4ec131d79..aa1dec8f7 100644 --- a/src/Ocelot/DependencyInjection/OcelotBuilder.cs +++ b/src/Ocelot/DependencyInjection/OcelotBuilder.cs @@ -36,6 +36,9 @@ using Ocelot.ServiceDiscovery.Providers; using Ocelot.WebSockets; using System.Reflection; +using System.Text.Encodings.Web; +using System.Text.Json.Serialization; +using System.Text.Unicode; namespace Ocelot.DependencyInjection; @@ -183,7 +186,15 @@ protected IMvcCoreBuilder AddDefaultAspNetServices(IMvcCoreBuilder builder, Asse return builder .AddApplicationPart(assembly) .AddControllersAsServices() - .AddAuthorization(); + .AddAuthorization() + .AddJsonOptions(op => + { + op.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles; + op.JsonSerializerOptions.NumberHandling = JsonNumberHandling.AllowReadingFromString; + op.JsonSerializerOptions.WriteIndented = false; + op.JsonSerializerOptions.PropertyNameCaseInsensitive = true; + op.JsonSerializerOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All); + }); } public IOcelotBuilder AddSingletonDefinedAggregator() From 4d14ebbbf0f4143d85ee3c8a953f79b46486a800 Mon Sep 17 00:00:00 2001 From: Mohammad Amin Pourmoradian Date: Fri, 19 Jul 2024 10:49:04 +0330 Subject: [PATCH 03/26] fix: AcceptanceTest ConsulServiceDiscovery --- .../ServiceDiscovery/ConsulServiceDiscoveryTests.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulServiceDiscoveryTests.cs b/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulServiceDiscoveryTests.cs index 42cec8572..ddadd76eb 100644 --- a/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulServiceDiscoveryTests.cs +++ b/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulServiceDiscoveryTests.cs @@ -624,6 +624,7 @@ private void GivenThereIsAFakeConsulServiceDiscoveryProvider(string url) var serviceName = pathMatch.Groups["serviceName"].Value; var services = _consulServices.Where(x => x.Service.Service == serviceName).ToList(); var json = JsonSerializer.Serialize(services, JsonSerializerOptionsExtensions.Web); + json = json.Replace("\"Name\":", "\"Node\":"); //} context.Response.Headers.Append("Content-Type", "application/json"); From 646b81c85b9715325cf6023c86448131401376e2 Mon Sep 17 00:00:00 2001 From: Mohsen Rajabi Date: Fri, 19 Jul 2024 10:52:03 +0330 Subject: [PATCH 04/26] fix: fix indent --- src/Ocelot/Infrastructure/JsonSerializerOptionsExtensions.cs | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/Ocelot/Infrastructure/JsonSerializerOptionsExtensions.cs b/src/Ocelot/Infrastructure/JsonSerializerOptionsExtensions.cs index b3c0fb526..7417ceb21 100644 --- a/src/Ocelot/Infrastructure/JsonSerializerOptionsExtensions.cs +++ b/src/Ocelot/Infrastructure/JsonSerializerOptionsExtensions.cs @@ -10,8 +10,6 @@ public static class JsonSerializerOptionsExtensions public static readonly JsonSerializerOptions Web = new() { PropertyNameCaseInsensitive = true, - //PropertyNamingPolicy = JsonNamingPolicy.CamelCase, - //DictionaryKeyPolicy = JsonNamingPolicy.CamelCase, NumberHandling = JsonNumberHandling.AllowReadingFromString, ReferenceHandler = ReferenceHandler.IgnoreCycles, WriteIndented = false, @@ -22,8 +20,6 @@ public static class JsonSerializerOptionsExtensions public static readonly JsonSerializerOptions WebWriteIndented = new() { PropertyNameCaseInsensitive = true, - //PropertyNamingPolicy = JsonNamingPolicy.CamelCase, - //DictionaryKeyPolicy = JsonNamingPolicy.CamelCase, NumberHandling = JsonNumberHandling.AllowReadingFromString, ReferenceHandler = ReferenceHandler.IgnoreCycles, WriteIndented = true, From fe5b2fda453939081dce9039269aef96aeb2be75 Mon Sep 17 00:00:00 2001 From: Mohsen Rajabi Date: Fri, 19 Jul 2024 11:07:04 +0330 Subject: [PATCH 05/26] feat: change un use --- .../ServiceDiscovery/ConsulServiceDiscoveryTests.cs | 4 ---- .../DependencyInjection/OcelotBuilderTests.cs | 5 +++++ 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulServiceDiscoveryTests.cs b/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulServiceDiscoveryTests.cs index ddadd76eb..351c8ae08 100644 --- a/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulServiceDiscoveryTests.cs +++ b/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulServiceDiscoveryTests.cs @@ -537,10 +537,6 @@ public MyConsulServiceBuilder(IHttpContextAccessor contextAccessor, IConsulClien { DownstreamPathTemplate = downstream ?? "/", DownstreamScheme = Uri.UriSchemeHttp, - DownstreamHostAndPorts = new List() - { - new FileHostAndPort("localhost",5000) - }, UpstreamPathTemplate = upstream ?? "/", UpstreamHttpMethod = httpMethods != null ? new(httpMethods) : new() { HttpMethods.Get }, UpstreamHost = upstreamHost, diff --git a/test/Ocelot.UnitTests/DependencyInjection/OcelotBuilderTests.cs b/test/Ocelot.UnitTests/DependencyInjection/OcelotBuilderTests.cs index 5d6321589..010751832 100644 --- a/test/Ocelot.UnitTests/DependencyInjection/OcelotBuilderTests.cs +++ b/test/Ocelot.UnitTests/DependencyInjection/OcelotBuilderTests.cs @@ -6,6 +6,7 @@ using Microsoft.AspNetCore.Mvc.ApplicationModels; using Microsoft.AspNetCore.Mvc.ApplicationParts; using Microsoft.AspNetCore.Mvc.Controllers; +using Microsoft.AspNetCore.Mvc.Infrastructure; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; @@ -322,6 +323,10 @@ private void CstorShouldUseDefaultBuilderToInitMvcCoreBuilder() .ShouldNotBeNull() .GetType().Name.ShouldBe("AuthorizationApplicationModelProvider"); + // use system text json + _serviceProvider.GetServices>() + .FirstOrDefault(s => s.GetType().Name == "SystemTextJsonResultExecutor") + .ShouldNotBeNull(); } [Fact] From d5c23c01b372a02a0d9bc3374a73161e1ccc7da8 Mon Sep 17 00:00:00 2001 From: Mohsen Rajabi Date: Fri, 19 Jul 2024 12:33:01 +0330 Subject: [PATCH 06/26] feat: add json benchmark --- .../JsonSerializerBenchmark.cs | 78 +++++++++++++++++++ .../Ocelot.Benchmarks.csproj | 5 ++ test/Ocelot.Benchmarks/Program.cs | 10 ++- 3 files changed, 92 insertions(+), 1 deletion(-) create mode 100644 test/Ocelot.Benchmarks/JsonSerializerBenchmark.cs diff --git a/test/Ocelot.Benchmarks/JsonSerializerBenchmark.cs b/test/Ocelot.Benchmarks/JsonSerializerBenchmark.cs new file mode 100644 index 000000000..6bc364360 --- /dev/null +++ b/test/Ocelot.Benchmarks/JsonSerializerBenchmark.cs @@ -0,0 +1,78 @@ +using BenchmarkDotNet.Jobs; +using Bogus; +using Newtonsoft.Json; +using JsonSerializer = System.Text.Json.JsonSerializer; + +namespace Ocelot.Benchmarks +{ + [SimpleJob(RuntimeMoniker.Net80)] + [Config(typeof(JsonSerializerBenchmark))] + public class JsonSerializerBenchmark : ManualConfig + { + private string _serializedTestUsers; + + private List _testUsers = new(); + + [Params(1000)] + public int Count { get; set; } + + [GlobalSetup] + public void GlobalSetup() + { + Faker faker = new Faker().CustomInstantiator( + f => + new User + { + UserId = Guid.NewGuid(), + FirstName = f.Name.FirstName(), + LastName = f.Name.LastName(), + FullName = f.Name.FullName(), + Username = f.Internet.UserName(f.Name.FirstName(), f.Name.LastName()), + Email = f.Internet.Email(f.Name.FirstName(), f.Name.LastName()) + } + ); + + _testUsers = faker.Generate(Count); + + _serializedTestUsers = JsonSerializer.Serialize(_testUsers); + } + + [Benchmark] + [BenchmarkCategory("Serialize", "Newtonsoft")] + public void NewtonsoftSerializeBigData() + { + _ = JsonConvert.SerializeObject(_testUsers); + } + + [Benchmark] + [BenchmarkCategory("Serialize", "Microsoft")] + public void MicrosoftSerializeBigData() + { + _ = JsonSerializer.Serialize(_testUsers); + } + + [Benchmark] + [BenchmarkCategory("Deserialize", "Newtonsoft")] + public void NewtonsoftDeserializeBigData() + { + _ = JsonConvert.DeserializeObject>(_serializedTestUsers); + } + + [Benchmark] + [BenchmarkCategory("Deserialize", "Microsoft")] + public void MicrosoftDeserializeBigData() + { + _ = JsonSerializer.Deserialize>(_serializedTestUsers); + } + } +} + +public class User +{ + public Guid UserId { get; set; } + public string FirstName { get; set; } + public string LastName { get; set; } + public string FullName { get; set; } + public string Username { get; set; } + public string Email { get; set; } +} diff --git a/test/Ocelot.Benchmarks/Ocelot.Benchmarks.csproj b/test/Ocelot.Benchmarks/Ocelot.Benchmarks.csproj index 378ed72e5..e4374e6f5 100644 --- a/test/Ocelot.Benchmarks/Ocelot.Benchmarks.csproj +++ b/test/Ocelot.Benchmarks/Ocelot.Benchmarks.csproj @@ -26,7 +26,12 @@ + + + + all + diff --git a/test/Ocelot.Benchmarks/Program.cs b/test/Ocelot.Benchmarks/Program.cs index bea66ff17..689d1fea6 100644 --- a/test/Ocelot.Benchmarks/Program.cs +++ b/test/Ocelot.Benchmarks/Program.cs @@ -17,7 +17,15 @@ public static void Main(string[] args) typeof(MsLoggerBenchmarks), typeof(PayloadBenchmarks), typeof(ResponseBenchmarks), + typeof(JsonSerializerBenchmark), }); - switcher.Run(args); + + var config = ManualConfig.Create(DefaultConfig.Instance) + .AddAnalyser(BenchmarkDotNet.Analysers.EnvironmentAnalyser.Default) + .AddExporter(BenchmarkDotNet.Exporters.MarkdownExporter.GitHub) + .AddDiagnoser(BenchmarkDotNet.Diagnosers.MemoryDiagnoser.Default) + .AddColumn(StatisticColumn.OperationsPerSecond); + + switcher.Run(args, config); } } From c7a641cb4699843edb22327ca5088d3abe9cb414 Mon Sep 17 00:00:00 2001 From: Mohsen Rajabi Date: Fri, 19 Jul 2024 12:36:30 +0330 Subject: [PATCH 07/26] feat: add json serialize result json --- test/Ocelot.Benchmarks/JsonSerializerBenchmark.cs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/test/Ocelot.Benchmarks/JsonSerializerBenchmark.cs b/test/Ocelot.Benchmarks/JsonSerializerBenchmark.cs index 6bc364360..23f79dbe0 100644 --- a/test/Ocelot.Benchmarks/JsonSerializerBenchmark.cs +++ b/test/Ocelot.Benchmarks/JsonSerializerBenchmark.cs @@ -65,6 +65,21 @@ public void MicrosoftDeserializeBigData() _ = JsonSerializer.Deserialize>(_serializedTestUsers); } } + + //BenchmarkDotNet v0.13.11, Windows 11 (10.0.22631.3880/23H2/2023Update/SunValley3) + //Intel Core i7-10870H CPU 2.20GHz, 1 CPU, 16 logical and 8 physical cores + // .NET SDK 8.0.303 + // [Host] : .NET 6.0.32 (6.0.3224.31407), X64 RyuJIT AVX2[AttachedDebugger] + // .NET 8.0 : .NET 8.0.7 (8.0.724.31311), X64 RyuJIT AVX2 + + // Job =.NET 8.0 Runtime=.NET 8.0 + + // | Method | Count | Mean | Error | StdDev | Median | Op/s | Gen0 | Gen1 | Gen2 | Allocated | + // |----------------------------- |------ |-----------:|---------:|----------:|-----------:|--------:|---------:|---------:|---------:|----------:| + // | MicrosoftDeserializeBigData | 1000 | 856.3 us | 53.98 us | 157.47 us | 797.1 us | 1,167.8 | 39.0625 | 13.6719 | - | 328.78 KB | + // | NewtonsoftDeserializeBigData | 1000 | 1,137.2 us | 18.74 us | 17.53 us | 1,132.8 us | 879.4 | 54.6875 | 17.5781 | - | 457.94 KB | + // | MicrosoftSerializeBigData | 1000 | 646.4 us | 12.72 us | 20.90 us | 645.7 us | 1,546.9 | 110.3516 | 110.3516 | 110.3516 | 350.02 KB | + // | NewtonsoftSerializeBigData | 1000 | 1,033.4 us | 19.37 us | 42.53 us | 1,022.8 us | 967.7 | 109.3750 | 109.3750 | 109.3750 | 837.82 KB | } public class User From 61247cc7495a631f11d359773f0a564bf1b0317e Mon Sep 17 00:00:00 2001 From: Mohsen Rajabi Date: Fri, 19 Jul 2024 12:37:07 +0330 Subject: [PATCH 08/26] fix --- test/Ocelot.Benchmarks/JsonSerializerBenchmark.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/test/Ocelot.Benchmarks/JsonSerializerBenchmark.cs b/test/Ocelot.Benchmarks/JsonSerializerBenchmark.cs index 23f79dbe0..35919a441 100644 --- a/test/Ocelot.Benchmarks/JsonSerializerBenchmark.cs +++ b/test/Ocelot.Benchmarks/JsonSerializerBenchmark.cs @@ -78,6 +78,7 @@ public void MicrosoftDeserializeBigData() // |----------------------------- |------ |-----------:|---------:|----------:|-----------:|--------:|---------:|---------:|---------:|----------:| // | MicrosoftDeserializeBigData | 1000 | 856.3 us | 53.98 us | 157.47 us | 797.1 us | 1,167.8 | 39.0625 | 13.6719 | - | 328.78 KB | // | NewtonsoftDeserializeBigData | 1000 | 1,137.2 us | 18.74 us | 17.53 us | 1,132.8 us | 879.4 | 54.6875 | 17.5781 | - | 457.94 KB | + // |==============================================================================================================================================| // | MicrosoftSerializeBigData | 1000 | 646.4 us | 12.72 us | 20.90 us | 645.7 us | 1,546.9 | 110.3516 | 110.3516 | 110.3516 | 350.02 KB | // | NewtonsoftSerializeBigData | 1000 | 1,033.4 us | 19.37 us | 42.53 us | 1,022.8 us | 967.7 | 109.3750 | 109.3750 | 109.3750 | 837.82 KB | } From 0048df86c1c729d6e8bed41656383fa582235284 Mon Sep 17 00:00:00 2001 From: Mohsen Rajabi Date: Fri, 19 Jul 2024 13:17:23 +0330 Subject: [PATCH 09/26] update doc --- docs/features/dependencyinjection.rst | 77 +++------------------------ 1 file changed, 8 insertions(+), 69 deletions(-) diff --git a/docs/features/dependencyinjection.rst b/docs/features/dependencyinjection.rst index dbd3437f6..abf974de2 100644 --- a/docs/features/dependencyinjection.rst +++ b/docs/features/dependencyinjection.rst @@ -132,7 +132,14 @@ Current `implementation + { + op.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles; + op.JsonSerializerOptions.NumberHandling = JsonNumberHandling.AllowReadingFromString; + op.JsonSerializerOptions.WriteIndented = false; + op.JsonSerializerOptions.PropertyNameCaseInsensitive = true; + op.JsonSerializerOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All); + }); } The method cannot be overridden. It is not virtual, and there is no way to override current behavior by inheritance. @@ -154,74 +161,6 @@ The next section shows you an example of designing custom Ocelot pipeline by cus .. _di-custom-builder: -Custom Builder --------------- - -**Goal**: Replace ``Newtonsoft.Json`` services with ``System.Text.Json`` services. - -Problem -^^^^^^^ - -The main `AddOcelot`_ method adds -`Newtonsoft JSON `_ services -by the ``AddNewtonsoftJson`` extension method in default builder (`AddDefaultAspNetServices`_ method). -The ``AddNewtonsoftJson`` method calling was introduced in old .NET and Ocelot releases which was necessary when Microsoft did not launch the ``System.Text.Json`` library, -but now it affects normal use, so we have an intention to solve the problem. - -Modern `JSON services `_ -out of `the box `_ -will help to configure JSON settings by the ``JsonSerializerOptions`` property for JSON formatters during (de)serialization. - -Solution -^^^^^^^^ - -We have the following methods in `ServiceCollectionExtensions`_ class: - -.. code-block:: csharp - - IOcelotBuilder AddOcelotUsingBuilder(this IServiceCollection services, Func customBuilder); - IOcelotBuilder AddOcelotUsingBuilder(this IServiceCollection services, IConfiguration configuration, Func customBuilder); - -These methods with custom builder allow you to use your any desired JSON library for (de)serialization. -But we are going to create custom ``MvcCoreBuilder`` with support of JSON services, such as ``System.Text.Json``. -To do that we need to call ``AddJsonOptions`` extension of the ``MvcCoreMvcCoreBuilderExtensions`` class -(NuGet package: `Microsoft.AspNetCore.Mvc.Core `_) in **Startup.cs**: - -.. code-block:: csharp - - using Microsoft.Extensions.DependencyInjection; - using Ocelot.DependencyInjection; - using System.Reflection; - - public class Startup - { - public void ConfigureServices(IServiceCollection services) - { - services - .AddLogging() - .AddMiddlewareAnalysis() - .AddWebEncoders() - // Add your custom builder - .AddOcelotUsingBuilder(MyCustomBuilder); - } - - private static IMvcCoreBuilder MyCustomBuilder(IMvcCoreBuilder builder, Assembly assembly) - { - return builder - .AddApplicationPart(assembly) - .AddControllersAsServices() - .AddAuthorization() - - // Replace AddNewtonsoftJson() by AddJsonOptions() - .AddJsonOptions(options => - { - options.JsonSerializerOptions.WriteIndented = true; // use System.Text.Json - }); - } - } - -The sample code provides settings to render JSON as indented text rather than compressed plain JSON text without spaces. -This is just one common use case, and you can add additional services to the builder. ------------------------------------------------------------------ From c30672f06d5d85669c86fa73b1b5350dad855262 Mon Sep 17 00:00:00 2001 From: Raman Maksimchuk Date: Mon, 22 Jul 2024 16:06:12 +0300 Subject: [PATCH 10/26] Revert file MessageInvokerPoolTests.cs ../test/Ocelot.UnitTests/Requester/MessageInvokerPoolTests.cs --- test/Ocelot.UnitTests/Requester/MessageInvokerPoolTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Ocelot.UnitTests/Requester/MessageInvokerPoolTests.cs b/test/Ocelot.UnitTests/Requester/MessageInvokerPoolTests.cs index 30bf5cd50..2e8ed678b 100644 --- a/test/Ocelot.UnitTests/Requester/MessageInvokerPoolTests.cs +++ b/test/Ocelot.UnitTests/Requester/MessageInvokerPoolTests.cs @@ -226,7 +226,7 @@ private void GivenARequestWithAUrlAndMethod(DownstreamRoute downstream, string u { _context.Items.UpsertDownstreamRoute(downstream); _context.Items.UpsertDownstreamRequest(new DownstreamRequest(new HttpRequestMessage - { RequestUri = new Uri(url), Method = method })); + { RequestUri = new Uri(url), Method = method })); } private async Task WhenICallTheClient(string url) From 62153826d8deba2c97819833e1da7d8c00242418 Mon Sep 17 00:00:00 2001 From: Raman Maksimchuk Date: Mon, 22 Jul 2024 16:50:48 +0300 Subject: [PATCH 11/26] Revert file ocelot.json ../test/Ocelot.IntegrationTests/ocelot.json --- test/Ocelot.IntegrationTests/ocelot.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Ocelot.IntegrationTests/ocelot.json b/test/Ocelot.IntegrationTests/ocelot.json index fdfcbaeef..39b71c1bb 100644 --- a/test/Ocelot.IntegrationTests/ocelot.json +++ b/test/Ocelot.IntegrationTests/ocelot.json @@ -33,7 +33,7 @@ "ClientWhitelist": [], "EnableRateLimiting": false, "Period": null, - "PeriodTimespan": 0, + "PeriodTimespan": 0.0, "Limit": 0 } } From dfbc87fcf5f36d5e3aec4e3b74f5a169fb2fe540 Mon Sep 17 00:00:00 2001 From: Raman Maksimchuk Date: Mon, 22 Jul 2024 16:59:46 +0300 Subject: [PATCH 12/26] Revert file Steps.cs ../test/Ocelot.AcceptanceTests/Steps.cs --- test/Ocelot.AcceptanceTests/Steps.cs | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/test/Ocelot.AcceptanceTests/Steps.cs b/test/Ocelot.AcceptanceTests/Steps.cs index 3e9c7880a..1dd81eb27 100644 --- a/test/Ocelot.AcceptanceTests/Steps.cs +++ b/test/Ocelot.AcceptanceTests/Steps.cs @@ -8,6 +8,7 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; +using Newtonsoft.Json; using Ocelot.AcceptanceTests.Caching; using Ocelot.AcceptanceTests.Properties; using Ocelot.Cache.CacheManager; @@ -16,7 +17,6 @@ using Ocelot.Configuration.File; using Ocelot.Configuration.Repository; using Ocelot.DependencyInjection; -using Ocelot.Infrastructure; using Ocelot.LoadBalancer.LoadBalancers; using Ocelot.Logging; using Ocelot.Middleware; @@ -28,8 +28,8 @@ using Serilog.Core; using System.IO.Compression; using System.Net.Http.Headers; +using System.Security.Policy; using System.Text; -using System.Text.Json; using static Ocelot.AcceptanceTests.HttpDelegatingHandlersTests; using ConfigurationBuilder = Microsoft.Extensions.Configuration.ConfigurationBuilder; using CookieHeaderValue = Microsoft.Net.Http.Headers.CookieHeaderValue; @@ -60,7 +60,7 @@ public Steps() : base() { _random = new Random(); _testId = Guid.NewGuid(); - _ocelotConfigFileName = $"{_testId:N}-{ConfigurationBuilderExtensions.PrimaryConfigFile}"; + _ocelotConfigFileName = $"{_testId:N}-{ConfigurationBuilderExtensions.PrimaryConfigFile}"; Files = new() { _ocelotConfigFileName }; Folders = new(); } @@ -150,10 +150,10 @@ public async Task StartFakeOcelotWithWebSockets() await _ocelotHost.StartAsync(); } - public void GivenThereIsAConfiguration(FileConfiguration fileConfiguration) + public void GivenThereIsAConfiguration(FileConfiguration fileConfiguration) => GivenThereIsAConfiguration(fileConfiguration, _ocelotConfigFileName); public void GivenThereIsAConfiguration(FileConfiguration from, string toFile) - { + { var json = SerializeJson(from, ref toFile); File.WriteAllText(toFile, json); } @@ -201,12 +201,12 @@ protected virtual void DeleteFolders() f.Delete(true); } } - catch (Exception e) - { - Console.WriteLine(e); - } + catch (Exception e) + { + Console.WriteLine(e); + } } - } + } public void ThenTheResponseBodyHeaderIs(string key, string value) { @@ -619,7 +619,7 @@ internal async Task GivenIHaveATokenWithForm(string url, IEnumerabl var response = await httpClient.PostAsync(tokenUrl, content); var responseContent = await response.Content.ReadAsStringAsync(); response.EnsureSuccessStatusCode(); - _token = JsonSerializer.Deserialize(responseContent, JsonSerializerOptionsExtensions.Web); + _token = JsonConvert.DeserializeObject(responseContent); return _token; } @@ -759,7 +759,7 @@ public void GivenThePostHasContentType(string postContent) public void GivenThePostHasGzipContent(object input) { - var json = JsonSerializer.Serialize(input, JsonSerializerOptionsExtensions.Web); + var json = JsonConvert.SerializeObject(input); var jsonBytes = Encoding.UTF8.GetBytes(json); var ms = new MemoryStream(); using (var gzip = new GZipStream(ms, CompressionMode.Compress, true)) From 12f1b2147120660d454e015d4497db8374d10ff5 Mon Sep 17 00:00:00 2001 From: Raman Maksimchuk Date: Mon, 22 Jul 2024 17:05:18 +0300 Subject: [PATCH 13/26] Apply changes in file Steps.cs ../test/Ocelot.AcceptanceTests/Steps.cs --- test/Ocelot.AcceptanceTests/Steps.cs | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/test/Ocelot.AcceptanceTests/Steps.cs b/test/Ocelot.AcceptanceTests/Steps.cs index 1dd81eb27..3e9c7880a 100644 --- a/test/Ocelot.AcceptanceTests/Steps.cs +++ b/test/Ocelot.AcceptanceTests/Steps.cs @@ -8,7 +8,6 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; -using Newtonsoft.Json; using Ocelot.AcceptanceTests.Caching; using Ocelot.AcceptanceTests.Properties; using Ocelot.Cache.CacheManager; @@ -17,6 +16,7 @@ using Ocelot.Configuration.File; using Ocelot.Configuration.Repository; using Ocelot.DependencyInjection; +using Ocelot.Infrastructure; using Ocelot.LoadBalancer.LoadBalancers; using Ocelot.Logging; using Ocelot.Middleware; @@ -28,8 +28,8 @@ using Serilog.Core; using System.IO.Compression; using System.Net.Http.Headers; -using System.Security.Policy; using System.Text; +using System.Text.Json; using static Ocelot.AcceptanceTests.HttpDelegatingHandlersTests; using ConfigurationBuilder = Microsoft.Extensions.Configuration.ConfigurationBuilder; using CookieHeaderValue = Microsoft.Net.Http.Headers.CookieHeaderValue; @@ -60,7 +60,7 @@ public Steps() : base() { _random = new Random(); _testId = Guid.NewGuid(); - _ocelotConfigFileName = $"{_testId:N}-{ConfigurationBuilderExtensions.PrimaryConfigFile}"; + _ocelotConfigFileName = $"{_testId:N}-{ConfigurationBuilderExtensions.PrimaryConfigFile}"; Files = new() { _ocelotConfigFileName }; Folders = new(); } @@ -150,10 +150,10 @@ public async Task StartFakeOcelotWithWebSockets() await _ocelotHost.StartAsync(); } - public void GivenThereIsAConfiguration(FileConfiguration fileConfiguration) + public void GivenThereIsAConfiguration(FileConfiguration fileConfiguration) => GivenThereIsAConfiguration(fileConfiguration, _ocelotConfigFileName); public void GivenThereIsAConfiguration(FileConfiguration from, string toFile) - { + { var json = SerializeJson(from, ref toFile); File.WriteAllText(toFile, json); } @@ -201,12 +201,12 @@ protected virtual void DeleteFolders() f.Delete(true); } } - catch (Exception e) - { - Console.WriteLine(e); - } + catch (Exception e) + { + Console.WriteLine(e); + } } - } + } public void ThenTheResponseBodyHeaderIs(string key, string value) { @@ -619,7 +619,7 @@ internal async Task GivenIHaveATokenWithForm(string url, IEnumerabl var response = await httpClient.PostAsync(tokenUrl, content); var responseContent = await response.Content.ReadAsStringAsync(); response.EnsureSuccessStatusCode(); - _token = JsonConvert.DeserializeObject(responseContent); + _token = JsonSerializer.Deserialize(responseContent, JsonSerializerOptionsExtensions.Web); return _token; } @@ -759,7 +759,7 @@ public void GivenThePostHasContentType(string postContent) public void GivenThePostHasGzipContent(object input) { - var json = JsonConvert.SerializeObject(input); + var json = JsonSerializer.Serialize(input, JsonSerializerOptionsExtensions.Web); var jsonBytes = Encoding.UTF8.GetBytes(json); var ms = new MemoryStream(); using (var gzip = new GZipStream(ms, CompressionMode.Compress, true)) From 86670478721bf8595efaacb30c45ff2f192991e5 Mon Sep 17 00:00:00 2001 From: Raman Maksimchuk Date: Mon, 22 Jul 2024 17:19:52 +0300 Subject: [PATCH 14/26] Revert file MessageInvokerPool.cs ../src/Ocelot/Requester/MessageInvokerPool.cs --- src/Ocelot/Requester/MessageInvokerPool.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Ocelot/Requester/MessageInvokerPool.cs b/src/Ocelot/Requester/MessageInvokerPool.cs index 7e6340838..130b4bccb 100644 --- a/src/Ocelot/Requester/MessageInvokerPool.cs +++ b/src/Ocelot/Requester/MessageInvokerPool.cs @@ -76,7 +76,7 @@ private HttpMessageHandler CreateHandler(DownstreamRoute downstreamRoute) UseCookies = downstreamRoute.HttpHandlerOptions.UseCookieContainer, UseProxy = downstreamRoute.HttpHandlerOptions.UseProxy, MaxConnectionsPerServer = downstreamRoute.HttpHandlerOptions.MaxConnectionsPerServer, - PooledConnectionLifetime = downstreamRoute.HttpHandlerOptions.PooledConnectionLifeTime + PooledConnectionLifetime = downstreamRoute.HttpHandlerOptions.PooledConnectionLifeTime, }; if (downstreamRoute.HttpHandlerOptions.UseCookieContainer) From ac74d643eb63b6235027d56f4d670f5613e74d42 Mon Sep 17 00:00:00 2001 From: Raman Maksimchuk Date: Mon, 22 Jul 2024 18:13:25 +0300 Subject: [PATCH 15/26] Code review by @raman-m --- .../DependencyInjection/ConfigurationBuilderExtensions.cs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/Ocelot/DependencyInjection/ConfigurationBuilderExtensions.cs b/src/Ocelot/DependencyInjection/ConfigurationBuilderExtensions.cs index 99aa1a507..f3c760b24 100644 --- a/src/Ocelot/DependencyInjection/ConfigurationBuilderExtensions.cs +++ b/src/Ocelot/DependencyInjection/ConfigurationBuilderExtensions.cs @@ -1,10 +1,11 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.Configuration.Memory; +using Microsoft.Extensions.Configuration.Memory; using Ocelot.Configuration.File; using Ocelot.Infrastructure; +using System.Text; using System.Text.Json; - + namespace Ocelot.DependencyInjection; /// @@ -146,7 +147,7 @@ private static string GetMergedOcelotJson(string folder, IWebHostEnvironment env return JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsExtensions.WebWriteIndented); } - + /// /// Adds Ocelot configuration by ready configuration object and writes JSON to the primary configuration file.
/// Finally, adds JSON file as configuration provider. From c6897c93dc0c6d054c5d8cca0f607a242866d03a Mon Sep 17 00:00:00 2001 From: Mohammad Amin Pourmoradian <46063083+MohammadAminPourmoradian@users.noreply.github.com> Date: Sun, 28 Jul 2024 13:44:19 +0330 Subject: [PATCH 16/26] fix: rename and format JsonSerializerOptions class --- .../ConsulFileConfigurationRepository.cs | 4 +-- .../DiskFileConfigurationRepository.cs | 4 +-- .../Repository/FileConfigurationPoller.cs | 18 ++++++------ .../ConfigurationBuilderExtensions.cs | 8 ++--- .../JsonSerializerOptionsExtensions.cs | 29 ------------------- .../JsonSerializerOptionsFactory.cs | 27 +++++++++++++++++ .../Metadata/DownstreamRouteExtensions.cs | 2 +- .../DistributedCacheRateLimitStorage.cs | 4 +-- .../Caching/CachingTests.cs | 4 +-- .../ConfigurationInConsulTests.cs | 6 ++-- .../ConsulConfigurationInConsulTests.cs | 10 +++---- .../ConsulServiceDiscoveryTests.cs | 4 +-- .../ServiceDiscovery/ConsulWebSocketTests.cs | 2 +- .../EurekaServiceDiscoveryTests.cs | 2 +- .../KubernetesServiceDiscoveryTests.cs | 2 +- test/Ocelot.AcceptanceTests/Steps.cs | 8 ++--- .../TwoDownstreamServicesTests.cs | 4 +-- .../AllTheThingsBenchmarks.cs | 4 +-- test/Ocelot.Benchmarks/MsLoggerBenchmarks.cs | 2 +- test/Ocelot.Benchmarks/PayloadBenchmarks.cs | 2 +- test/Ocelot.Benchmarks/ResponseBenchmarks.cs | 2 +- test/Ocelot.Benchmarks/SerilogBenchmarks.cs | 2 +- .../AdministrationTests.cs | 14 ++++----- .../CacheManagerTests.cs | 8 ++--- test/Ocelot.IntegrationTests/HeaderTests.cs | 6 ++-- .../ThreadSafeHeadersTests.cs | 2 +- .../CustomOcelotMiddleware.cs | 2 +- .../DiskFileConfigurationRepositoryTests.cs | 10 +++---- .../ConsulFileConfigurationRepositoryTests.cs | 12 ++++---- test/Ocelot.UnitTests/Consul/ConsulTests.cs | 2 +- .../ConfigurationBuilderExtensionsTests.cs | 2 +- test/Ocelot.UnitTests/Kubernetes/KubeTests.cs | 2 +- 32 files changed, 104 insertions(+), 106 deletions(-) delete mode 100644 src/Ocelot/Infrastructure/JsonSerializerOptionsExtensions.cs create mode 100644 src/Ocelot/Infrastructure/JsonSerializerOptionsFactory.cs diff --git a/src/Ocelot.Provider.Consul/ConsulFileConfigurationRepository.cs b/src/Ocelot.Provider.Consul/ConsulFileConfigurationRepository.cs index 79937962f..e79245a1b 100644 --- a/src/Ocelot.Provider.Consul/ConsulFileConfigurationRepository.cs +++ b/src/Ocelot.Provider.Consul/ConsulFileConfigurationRepository.cs @@ -54,14 +54,14 @@ public async Task> Get() var bytes = queryResult.Response.Value; var json = Encoding.UTF8.GetString(bytes); - var consulConfig = JsonSerializer.Deserialize(json, JsonSerializerOptionsExtensions.Web); + var consulConfig = JsonSerializer.Deserialize(json, JsonSerializerOptionsFactory.Web); return new OkResponse(consulConfig); } public async Task Set(FileConfiguration ocelotConfiguration) { - var json = JsonSerializer.Serialize(ocelotConfiguration, JsonSerializerOptionsExtensions.WebWriteIndented); + var json = JsonSerializer.Serialize(ocelotConfiguration, JsonSerializerOptionsFactory.WebWriteIndented); var bytes = Encoding.UTF8.GetBytes(json); var kvPair = new KVPair(_configurationKey) { diff --git a/src/Ocelot/Configuration/Repository/DiskFileConfigurationRepository.cs b/src/Ocelot/Configuration/Repository/DiskFileConfigurationRepository.cs index e3935b4b9..7fd43a688 100644 --- a/src/Ocelot/Configuration/Repository/DiskFileConfigurationRepository.cs +++ b/src/Ocelot/Configuration/Repository/DiskFileConfigurationRepository.cs @@ -50,14 +50,14 @@ public Task> Get() jsonConfiguration = FileSys.ReadAllText(_environmentFile.FullName); } - var fileConfiguration = JsonSerializer.Deserialize(jsonConfiguration, JsonSerializerOptionsExtensions.Web); + var fileConfiguration = JsonSerializer.Deserialize(jsonConfiguration, JsonSerializerOptionsFactory.Web); return Task.FromResult>(new OkResponse(fileConfiguration)); } public Task Set(FileConfiguration fileConfiguration) { - var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsExtensions.WebWriteIndented); + var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsFactory.WebWriteIndented); lock (_lock) { diff --git a/src/Ocelot/Configuration/Repository/FileConfigurationPoller.cs b/src/Ocelot/Configuration/Repository/FileConfigurationPoller.cs index ec6445bf3..abff81463 100644 --- a/src/Ocelot/Configuration/Repository/FileConfigurationPoller.cs +++ b/src/Ocelot/Configuration/Repository/FileConfigurationPoller.cs @@ -90,15 +90,15 @@ private async Task Poll() _logger.LogInformation("Finished polling"); } - /// - /// We could do object comparison here but performance isnt really a problem. This might be an issue one day!. - /// - /// hash of the config. - private static string ToJson(FileConfiguration config) - { - var currentHash = JsonSerializer.Serialize(config, JsonSerializerOptionsExtensions.Web); - return currentHash; - } + /// + /// We could do object comparison here but performance isnt really a problem. This might be an issue one day!. + /// + /// hash of the config. + private static string ToJson(FileConfiguration config) + { + var currentHash = JsonSerializer.Serialize(config, JsonSerializerOptionsFactory.Web); + return currentHash; + } public void Dispose() { diff --git a/src/Ocelot/DependencyInjection/ConfigurationBuilderExtensions.cs b/src/Ocelot/DependencyInjection/ConfigurationBuilderExtensions.cs index f3c760b24..1e3915704 100644 --- a/src/Ocelot/DependencyInjection/ConfigurationBuilderExtensions.cs +++ b/src/Ocelot/DependencyInjection/ConfigurationBuilderExtensions.cs @@ -5,7 +5,7 @@ using Ocelot.Infrastructure; using System.Text; using System.Text.Json; - + namespace Ocelot.DependencyInjection; /// @@ -134,7 +134,7 @@ private static string GetMergedOcelotJson(string folder, IWebHostEnvironment env } var lines = File.ReadAllText(file.FullName); - var config = JsonSerializer.Deserialize(lines, JsonSerializerOptionsExtensions.Web); + var config = JsonSerializer.Deserialize(lines, JsonSerializerOptionsFactory.Web); if (file.Name.Equals(globalFileInfo.Name, StringComparison.OrdinalIgnoreCase) && file.FullName.Equals(globalFileInfo.FullName, StringComparison.OrdinalIgnoreCase)) { @@ -145,7 +145,7 @@ private static string GetMergedOcelotJson(string folder, IWebHostEnvironment env fileConfiguration.Routes.AddRange(config.Routes); } - return JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsExtensions.WebWriteIndented); + return JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsFactory.WebWriteIndented); } /// @@ -162,7 +162,7 @@ private static string GetMergedOcelotJson(string folder, IWebHostEnvironment env public static IConfigurationBuilder AddOcelot(this IConfigurationBuilder builder, FileConfiguration fileConfiguration, string primaryConfigFile = null, bool? optional = null, bool? reloadOnChange = null) // optional injections { - var json = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsExtensions.WebWriteIndented); + var json = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsFactory.WebWriteIndented); return AddOcelotJsonFile(builder, json, primaryConfigFile, optional, reloadOnChange); } diff --git a/src/Ocelot/Infrastructure/JsonSerializerOptionsExtensions.cs b/src/Ocelot/Infrastructure/JsonSerializerOptionsExtensions.cs deleted file mode 100644 index 7417ceb21..000000000 --- a/src/Ocelot/Infrastructure/JsonSerializerOptionsExtensions.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System.Text.Encodings.Web; -using System.Text.Json; -using System.Text.Json.Serialization; -using System.Text.Unicode; - -namespace Ocelot.Infrastructure -{ - public static class JsonSerializerOptionsExtensions - { - public static readonly JsonSerializerOptions Web = new() - { - PropertyNameCaseInsensitive = true, - NumberHandling = JsonNumberHandling.AllowReadingFromString, - ReferenceHandler = ReferenceHandler.IgnoreCycles, - WriteIndented = false, - Encoder = JavaScriptEncoder.Create(UnicodeRanges.All), - - }; - - public static readonly JsonSerializerOptions WebWriteIndented = new() - { - PropertyNameCaseInsensitive = true, - NumberHandling = JsonNumberHandling.AllowReadingFromString, - ReferenceHandler = ReferenceHandler.IgnoreCycles, - WriteIndented = true, - Encoder = JavaScriptEncoder.Create(UnicodeRanges.All) - }; - } -} diff --git a/src/Ocelot/Infrastructure/JsonSerializerOptionsFactory.cs b/src/Ocelot/Infrastructure/JsonSerializerOptionsFactory.cs new file mode 100644 index 000000000..1434b21eb --- /dev/null +++ b/src/Ocelot/Infrastructure/JsonSerializerOptionsFactory.cs @@ -0,0 +1,27 @@ +using System.Text.Encodings.Web; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Text.Unicode; + +namespace Ocelot.Infrastructure; + +public static class JsonSerializerOptionsFactory +{ + public static readonly JsonSerializerOptions Web = new() + { + Encoder = JavaScriptEncoder.Create(UnicodeRanges.All), + NumberHandling = JsonNumberHandling.AllowReadingFromString, + PropertyNameCaseInsensitive = true, + ReferenceHandler = ReferenceHandler.IgnoreCycles, + WriteIndented = false + }; + + public static readonly JsonSerializerOptions WebWriteIndented = new() + { + Encoder = JavaScriptEncoder.Create(UnicodeRanges.All), + NumberHandling = JsonNumberHandling.AllowReadingFromString, + PropertyNameCaseInsensitive = true, + ReferenceHandler = ReferenceHandler.IgnoreCycles, + WriteIndented = true + }; +} diff --git a/src/Ocelot/Metadata/DownstreamRouteExtensions.cs b/src/Ocelot/Metadata/DownstreamRouteExtensions.cs index b9c351f0c..9ee87b83a 100644 --- a/src/Ocelot/Metadata/DownstreamRouteExtensions.cs +++ b/src/Ocelot/Metadata/DownstreamRouteExtensions.cs @@ -74,7 +74,7 @@ public static T GetMetadata(this DownstreamRoute downstreamRoute, string key, } return (T)ConvertTo(typeof(T), metadataValue, downstreamRoute.MetadataOptions, - jsonSerializerOptions ?? JsonSerializerOptionsExtensions.Web); + jsonSerializerOptions ?? JsonSerializerOptionsFactory.Web); } /// diff --git a/src/Ocelot/RateLimiting/DistributedCacheRateLimitStorage.cs b/src/Ocelot/RateLimiting/DistributedCacheRateLimitStorage.cs index 6a6a3057d..2ab786eb2 100644 --- a/src/Ocelot/RateLimiting/DistributedCacheRateLimitStorage.cs +++ b/src/Ocelot/RateLimiting/DistributedCacheRateLimitStorage.cs @@ -17,7 +17,7 @@ public class DistributedCacheRateLimitStorage : IRateLimitStorage public DistributedCacheRateLimitStorage(IDistributedCache memoryCache) => _memoryCache = memoryCache; public void Set(string id, RateLimitCounter counter, TimeSpan expirationTime) - => _memoryCache.SetString(id, JsonSerializer.Serialize(counter, JsonSerializerOptionsExtensions.Web), new DistributedCacheEntryOptions().SetAbsoluteExpiration(expirationTime)); + => _memoryCache.SetString(id, JsonSerializer.Serialize(counter, JsonSerializerOptionsFactory.Web), new DistributedCacheEntryOptions().SetAbsoluteExpiration(expirationTime)); public bool Exists(string id) => !string.IsNullOrEmpty(_memoryCache.GetString(id)); @@ -25,7 +25,7 @@ public void Set(string id, RateLimitCounter counter, TimeSpan expirationTime) { var stored = _memoryCache.GetString(id); return !string.IsNullOrEmpty(stored) - ? JsonSerializer.Deserialize(stored, JsonSerializerOptionsExtensions.Web) + ? JsonSerializer.Deserialize(stored, JsonSerializerOptionsFactory.Web) : null; } diff --git a/test/Ocelot.AcceptanceTests/Caching/CachingTests.cs b/test/Ocelot.AcceptanceTests/Caching/CachingTests.cs index dfbe07679..86fd1dcb5 100644 --- a/test/Ocelot.AcceptanceTests/Caching/CachingTests.cs +++ b/test/Ocelot.AcceptanceTests/Caching/CachingTests.cs @@ -299,7 +299,7 @@ private void ThenTheCounterValueShouldBe(int expected) LastName = "Test", }; - var testBody1String = JsonSerializer.Serialize(testBody1, JsonSerializerOptionsExtensions.Web); + var testBody1String = JsonSerializer.Serialize(testBody1, JsonSerializerOptionsFactory.Web); var testBody2 = new TestBody { @@ -309,7 +309,7 @@ private void ThenTheCounterValueShouldBe(int expected) LastName = "Test", }; - var testBody2String = JsonSerializer.Serialize(testBody2, JsonSerializerOptionsExtensions.Web); + var testBody2String = JsonSerializer.Serialize(testBody2, JsonSerializerOptionsFactory.Web); return (testBody1String, testBody2String); } diff --git a/test/Ocelot.AcceptanceTests/Configuration/ConfigurationInConsulTests.cs b/test/Ocelot.AcceptanceTests/Configuration/ConfigurationInConsulTests.cs index a595c0bc4..3ec1d052b 100644 --- a/test/Ocelot.AcceptanceTests/Configuration/ConfigurationInConsulTests.cs +++ b/test/Ocelot.AcceptanceTests/Configuration/ConfigurationInConsulTests.cs @@ -130,7 +130,7 @@ private Task GivenThereIsAFakeConsulServiceDiscoveryProvider(string url, string { if (context.Request.Method.ToLower() == "get" && context.Request.Path.Value == "/v1/kv/InternalConfiguration") { - var json = JsonSerializer.Serialize(_config, JsonSerializerOptionsExtensions.Web); + var json = JsonSerializer.Serialize(_config, JsonSerializerOptionsFactory.Web); var bytes = Encoding.UTF8.GetBytes(json); @@ -150,9 +150,9 @@ private Task GivenThereIsAFakeConsulServiceDiscoveryProvider(string url, string // var json = reader.ReadToEnd(); var json = await reader.ReadToEndAsync(); - _config = JsonSerializer.Deserialize(json, JsonSerializerOptionsExtensions.Web); + _config = JsonSerializer.Deserialize(json, JsonSerializerOptionsFactory.Web); - var response = JsonSerializer.Serialize(true, JsonSerializerOptionsExtensions.Web); + var response = JsonSerializer.Serialize(true, JsonSerializerOptionsFactory.Web); await context.Response.WriteAsync(response); } diff --git a/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulConfigurationInConsulTests.cs b/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulConfigurationInConsulTests.cs index 5bfa4e923..a90d46876 100644 --- a/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulConfigurationInConsulTests.cs +++ b/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulConfigurationInConsulTests.cs @@ -386,14 +386,14 @@ private Task GivenThereIsAFakeConsulServiceDiscoveryProvider(string url, string { if (context.Request.Method.ToLower() == "get" && context.Request.Path.Value == "/v1/kv/InternalConfiguration") { - var json = JsonSerializer.Serialize(_config, JsonSerializerOptionsExtensions.Web); + var json = JsonSerializer.Serialize(_config, JsonSerializerOptionsFactory.Web); var bytes = Encoding.UTF8.GetBytes(json); var base64 = Convert.ToBase64String(bytes); var kvp = new FakeConsulGetResponse(base64); - json = JsonSerializer.Serialize(new[] { kvp }, JsonSerializerOptionsExtensions.Web); + json = JsonSerializer.Serialize(new[] { kvp }, JsonSerializerOptionsFactory.Web); context.Response.Headers.Append("Content-Type", "application/json"); await context.Response.WriteAsync(json); } @@ -407,9 +407,9 @@ private Task GivenThereIsAFakeConsulServiceDiscoveryProvider(string url, string // var json = reader.ReadToEnd(); var json = await reader.ReadToEndAsync(); - _config = JsonSerializer.Deserialize(json, JsonSerializerOptionsExtensions.Web); + _config = JsonSerializer.Deserialize(json, JsonSerializerOptionsFactory.Web); - var response = JsonSerializer.Serialize(true, JsonSerializerOptionsExtensions.Web); + var response = JsonSerializer.Serialize(true, JsonSerializerOptionsFactory.Web); await context.Response.WriteAsync(response); } @@ -421,7 +421,7 @@ private Task GivenThereIsAFakeConsulServiceDiscoveryProvider(string url, string } else if (context.Request.Path.Value == $"/v1/health/service/{serviceName}") { - var json = JsonSerializer.Serialize(_consulServices, JsonSerializerOptionsExtensions.Web); + var json = JsonSerializer.Serialize(_consulServices, JsonSerializerOptionsFactory.Web); context.Response.Headers.Append("Content-Type", "application/json"); await context.Response.WriteAsync(json); } diff --git a/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulServiceDiscoveryTests.cs b/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulServiceDiscoveryTests.cs index 351c8ae08..ed49bdb36 100644 --- a/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulServiceDiscoveryTests.cs +++ b/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulServiceDiscoveryTests.cs @@ -619,7 +619,7 @@ private void GivenThereIsAFakeConsulServiceDiscoveryProvider(string url) // Use the parsed service name to filter the registered Consul services var serviceName = pathMatch.Groups["serviceName"].Value; var services = _consulServices.Where(x => x.Service.Service == serviceName).ToList(); - var json = JsonSerializer.Serialize(services, JsonSerializerOptionsExtensions.Web); + var json = JsonSerializer.Serialize(services, JsonSerializerOptionsFactory.Web); json = json.Replace("\"Name\":", "\"Node\":"); //} @@ -632,7 +632,7 @@ private void GivenThereIsAFakeConsulServiceDiscoveryProvider(string url) { //_counterNodes++; int count = Interlocked.Increment(ref _counterNodes); - var json = JsonSerializer.Serialize(_consulNodes, JsonSerializerOptionsExtensions.Web); + var json = JsonSerializer.Serialize(_consulNodes, JsonSerializerOptionsFactory.Web); context.Response.Headers.Append("Content-Type", "application/json"); await context.Response.WriteAsync(json); } diff --git a/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulWebSocketTests.cs b/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulWebSocketTests.cs index 0cf55e383..eed86bb96 100644 --- a/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulWebSocketTests.cs +++ b/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulWebSocketTests.cs @@ -175,7 +175,7 @@ private void GivenThereIsAFakeConsulServiceDiscoveryProvider(int port, string se { if (context.Request.Path.Value == $"/v1/health/service/{serviceName}") { - var json = JsonSerializer.Serialize(_serviceEntries, JsonSerializerOptionsExtensions.Web); + var json = JsonSerializer.Serialize(_serviceEntries, JsonSerializerOptionsFactory.Web); context.Response.Headers.Append("Content-Type", "application/json"); await context.Response.WriteAsync(json); } diff --git a/test/Ocelot.AcceptanceTests/ServiceDiscovery/EurekaServiceDiscoveryTests.cs b/test/Ocelot.AcceptanceTests/ServiceDiscovery/EurekaServiceDiscoveryTests.cs index 729a6a6f6..484e71cff 100644 --- a/test/Ocelot.AcceptanceTests/ServiceDiscovery/EurekaServiceDiscoveryTests.cs +++ b/test/Ocelot.AcceptanceTests/ServiceDiscovery/EurekaServiceDiscoveryTests.cs @@ -144,7 +144,7 @@ private void GivenThereIsAFakeEurekaServiceDiscoveryProvider(string url, string }, }; - var json = JsonSerializer.Serialize(applications, JsonSerializerOptionsExtensions.Web); + var json = JsonSerializer.Serialize(applications, JsonSerializerOptionsFactory.Web); context.Response.Headers.Append("Content-Type", "application/json"); await context.Response.WriteAsync(json); } diff --git a/test/Ocelot.AcceptanceTests/ServiceDiscovery/KubernetesServiceDiscoveryTests.cs b/test/Ocelot.AcceptanceTests/ServiceDiscovery/KubernetesServiceDiscoveryTests.cs index 0adc2eb2f..9857760e0 100644 --- a/test/Ocelot.AcceptanceTests/ServiceDiscovery/KubernetesServiceDiscoveryTests.cs +++ b/test/Ocelot.AcceptanceTests/ServiceDiscovery/KubernetesServiceDiscoveryTests.cs @@ -295,7 +295,7 @@ private void GivenThereIsAFakeKubernetesProvider(EndpointsV1 endpoints, bool isS } endpoints.Metadata.Generation = _k8sServiceGeneration; - json = JsonSerializer.Serialize(endpoints, JsonSerializerOptionsExtensions.Web); + json = JsonSerializer.Serialize(endpoints, JsonSerializerOptionsFactory.Web); } if (context.Request.Headers.TryGetValue("Authorization", out var values)) diff --git a/test/Ocelot.AcceptanceTests/Steps.cs b/test/Ocelot.AcceptanceTests/Steps.cs index 3e9c7880a..c73fab9c0 100644 --- a/test/Ocelot.AcceptanceTests/Steps.cs +++ b/test/Ocelot.AcceptanceTests/Steps.cs @@ -28,7 +28,7 @@ using Serilog.Core; using System.IO.Compression; using System.Net.Http.Headers; -using System.Text; +using System.Text; using System.Text.Json; using static Ocelot.AcceptanceTests.HttpDelegatingHandlersTests; using ConfigurationBuilder = Microsoft.Extensions.Configuration.ConfigurationBuilder; @@ -166,7 +166,7 @@ protected string SerializeJson(FileConfiguration from, ref string toFile) { toFile ??= _ocelotConfigFileName; Files.Add(toFile); // register for disposing - return JsonSerializer.Serialize(from, JsonSerializerOptionsExtensions.WebWriteIndented); + return JsonSerializer.Serialize(from, JsonSerializerOptionsFactory.WebWriteIndented); } protected virtual void DeleteFiles() @@ -619,7 +619,7 @@ internal async Task GivenIHaveATokenWithForm(string url, IEnumerabl var response = await httpClient.PostAsync(tokenUrl, content); var responseContent = await response.Content.ReadAsStringAsync(); response.EnsureSuccessStatusCode(); - _token = JsonSerializer.Deserialize(responseContent, JsonSerializerOptionsExtensions.Web); + _token = JsonSerializer.Deserialize(responseContent, JsonSerializerOptionsFactory.Web); return _token; } @@ -759,7 +759,7 @@ public void GivenThePostHasContentType(string postContent) public void GivenThePostHasGzipContent(object input) { - var json = JsonSerializer.Serialize(input, JsonSerializerOptionsExtensions.Web); + var json = JsonSerializer.Serialize(input, JsonSerializerOptionsFactory.Web); var jsonBytes = Encoding.UTF8.GetBytes(json); var ms = new MemoryStream(); using (var gzip = new GZipStream(ms, CompressionMode.Compress, true)) diff --git a/test/Ocelot.AcceptanceTests/TwoDownstreamServicesTests.cs b/test/Ocelot.AcceptanceTests/TwoDownstreamServicesTests.cs index 7bdb5d081..dcb93c1f2 100644 --- a/test/Ocelot.AcceptanceTests/TwoDownstreamServicesTests.cs +++ b/test/Ocelot.AcceptanceTests/TwoDownstreamServicesTests.cs @@ -1,6 +1,6 @@ using Consul; using Microsoft.AspNetCore.Http; -using Ocelot.Configuration.File; +using Ocelot.Configuration.File; using Ocelot.Infrastructure; using System.Text.Json; @@ -97,7 +97,7 @@ private void GivenThereIsAFakeConsulServiceDiscoveryProvider(string url) { if (context.Request.Path.Value == "/v1/health/service/product") { - var json = JsonSerializer.Serialize(_serviceEntries, JsonSerializerOptionsExtensions.Web); + var json = JsonSerializer.Serialize(_serviceEntries, JsonSerializerOptionsFactory.Web); context.Response.Headers.Append("Content-Type", "application/json"); await context.Response.WriteAsync(json); } diff --git a/test/Ocelot.Benchmarks/AllTheThingsBenchmarks.cs b/test/Ocelot.Benchmarks/AllTheThingsBenchmarks.cs index 84179b264..4694c2c82 100644 --- a/test/Ocelot.Benchmarks/AllTheThingsBenchmarks.cs +++ b/test/Ocelot.Benchmarks/AllTheThingsBenchmarks.cs @@ -6,7 +6,7 @@ using Ocelot.Configuration.File; using Ocelot.DependencyInjection; using Ocelot.Infrastructure; -using Ocelot.Middleware; +using Ocelot.Middleware; using System.Text.Json; namespace Ocelot.Benchmarks; @@ -113,7 +113,7 @@ public static void GivenThereIsAConfiguration(FileConfiguration fileConfiguratio { var configurationPath = Path.Combine(AppContext.BaseDirectory, "ocelot.json"); - var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsExtensions.Web); + var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsFactory.Web); if (File.Exists(configurationPath)) { diff --git a/test/Ocelot.Benchmarks/MsLoggerBenchmarks.cs b/test/Ocelot.Benchmarks/MsLoggerBenchmarks.cs index 174edbbe9..11f325210 100644 --- a/test/Ocelot.Benchmarks/MsLoggerBenchmarks.cs +++ b/test/Ocelot.Benchmarks/MsLoggerBenchmarks.cs @@ -163,7 +163,7 @@ public static void GivenThereIsAConfiguration(FileConfiguration fileConfiguratio { var configurationPath = Path.Combine(AppContext.BaseDirectory, "ocelot.json"); - var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsExtensions.Web); + var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsFactory.Web); if (File.Exists(configurationPath)) { diff --git a/test/Ocelot.Benchmarks/PayloadBenchmarks.cs b/test/Ocelot.Benchmarks/PayloadBenchmarks.cs index 2acf8d2be..bf58087e6 100644 --- a/test/Ocelot.Benchmarks/PayloadBenchmarks.cs +++ b/test/Ocelot.Benchmarks/PayloadBenchmarks.cs @@ -221,7 +221,7 @@ private void GivenOcelotIsRunning(string url) public static void GivenThereIsAConfiguration(FileConfiguration fileConfiguration) { var configurationPath = Path.Combine(AppContext.BaseDirectory, ConfigurationBuilderExtensions.PrimaryConfigFile); - var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsExtensions.Web); + var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsFactory.Web); if (File.Exists(configurationPath)) { diff --git a/test/Ocelot.Benchmarks/ResponseBenchmarks.cs b/test/Ocelot.Benchmarks/ResponseBenchmarks.cs index 205d1c564..75c00d143 100644 --- a/test/Ocelot.Benchmarks/ResponseBenchmarks.cs +++ b/test/Ocelot.Benchmarks/ResponseBenchmarks.cs @@ -222,7 +222,7 @@ private void GivenOcelotIsRunning(string url) public static void GivenThereIsAConfiguration(FileConfiguration fileConfiguration) { var configurationPath = Path.Combine(AppContext.BaseDirectory, ConfigurationBuilderExtensions.PrimaryConfigFile); - var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsExtensions.Web); + var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsFactory.Web); if (File.Exists(configurationPath)) { diff --git a/test/Ocelot.Benchmarks/SerilogBenchmarks.cs b/test/Ocelot.Benchmarks/SerilogBenchmarks.cs index 15218b19b..d6fff6971 100644 --- a/test/Ocelot.Benchmarks/SerilogBenchmarks.cs +++ b/test/Ocelot.Benchmarks/SerilogBenchmarks.cs @@ -194,7 +194,7 @@ public static void GivenThereIsAConfiguration(FileConfiguration fileConfiguratio { var configurationPath = Path.Combine(AppContext.BaseDirectory, "ocelot.json"); - var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsExtensions.Web); + var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsFactory.Web); if (File.Exists(configurationPath)) { diff --git a/test/Ocelot.IntegrationTests/AdministrationTests.cs b/test/Ocelot.IntegrationTests/AdministrationTests.cs index 7f7b84e54..921597b87 100644 --- a/test/Ocelot.IntegrationTests/AdministrationTests.cs +++ b/test/Ocelot.IntegrationTests/AdministrationTests.cs @@ -343,12 +343,12 @@ private static void ThenTheConfigurationIsSavedCorrectly(FileConfiguration expec { var ocelotJsonPath = $"{AppContext.BaseDirectory}ocelot.json"; var resultText = File.ReadAllText(ocelotJsonPath); - var expectedText = JsonSerializer.Serialize(expected, JsonSerializerOptionsExtensions.WebWriteIndented); + var expectedText = JsonSerializer.Serialize(expected, JsonSerializerOptionsFactory.WebWriteIndented); resultText.ShouldBe(expectedText); var environmentSpecificPath = $"{AppContext.BaseDirectory}/ocelot.Production.json"; resultText = File.ReadAllText(environmentSpecificPath); - expectedText = JsonSerializer.Serialize(expected, JsonSerializerOptionsExtensions.WebWriteIndented); + expectedText = JsonSerializer.Serialize(expected, JsonSerializerOptionsFactory.WebWriteIndented); resultText.ShouldBe(expectedText); } @@ -524,7 +524,7 @@ private async Task GivenIHaveAToken(string url) var response = await httpClient.PostAsync($"{url}/connect/token", content); var responseContent = await response.Content.ReadAsStringAsync(); response.EnsureSuccessStatusCode(); - _token = JsonSerializer.Deserialize(responseContent, JsonSerializerOptionsExtensions.Web); + _token = JsonSerializer.Deserialize(responseContent, JsonSerializerOptionsFactory.Web); } private async Task GivenThereIsAnIdentityServerOn(string url, string apiName) @@ -641,7 +641,7 @@ private async Task WhenIGetUrlOnTheSecondOcelot(string url) private async Task WhenIPostOnTheApiGateway(string url, FileConfiguration updatedConfiguration) { - var json = JsonSerializer.Serialize(updatedConfiguration, JsonSerializerOptionsExtensions.Web); + var json = JsonSerializer.Serialize(updatedConfiguration, JsonSerializerOptionsFactory.Web); var content = new StringContent(json); content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); _response = await _httpClient.PostAsync(url, content); @@ -655,7 +655,7 @@ private async Task ThenTheResponseBodyShouldBe(string expected) private async Task ThenTheResponseShouldBe(FileConfiguration expecteds) { - var response = JsonSerializer.Deserialize(await _response.Content.ReadAsStringAsync(), JsonSerializerOptionsExtensions.Web); + var response = JsonSerializer.Deserialize(await _response.Content.ReadAsStringAsync(), JsonSerializerOptionsFactory.Web); response.GlobalConfiguration.RequestIdKey.ShouldBe(expecteds.GlobalConfiguration.RequestIdKey); response.GlobalConfiguration.ServiceDiscoveryProvider.Scheme.ShouldBe(expecteds.GlobalConfiguration.ServiceDiscoveryProvider.Scheme); @@ -699,7 +699,7 @@ private async Task GivenIHaveAnOcelotToken(string adminPath) var response = await _httpClient.PostAsync(tokenUrl, content); var responseContent = await response.Content.ReadAsStringAsync(); response.EnsureSuccessStatusCode(); - _token = JsonSerializer.Deserialize(responseContent, JsonSerializerOptionsExtensions.Web); + _token = JsonSerializer.Deserialize(responseContent, JsonSerializerOptionsFactory.Web); var configPath = $"{adminPath}/.well-known/openid-configuration"; response = await _httpClient.GetAsync(configPath); response.EnsureSuccessStatusCode(); @@ -826,7 +826,7 @@ private static async Task GivenThereIsAConfiguration(FileConfiguration fileConfi { var configurationPath = $"{Directory.GetCurrentDirectory()}/ocelot.json"; - var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsExtensions.Web); + var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsFactory.Web); if (File.Exists(configurationPath)) { diff --git a/test/Ocelot.IntegrationTests/CacheManagerTests.cs b/test/Ocelot.IntegrationTests/CacheManagerTests.cs index 518e9141e..484a4220c 100644 --- a/test/Ocelot.IntegrationTests/CacheManagerTests.cs +++ b/test/Ocelot.IntegrationTests/CacheManagerTests.cs @@ -6,11 +6,11 @@ using Ocelot.Administration; using Ocelot.Cache.CacheManager; using Ocelot.Configuration.File; -using Ocelot.DependencyInjection; +using Ocelot.DependencyInjection; using Ocelot.Infrastructure; using Ocelot.Middleware; using System.Net; -using System.Net.Http.Headers; +using System.Net.Http.Headers; using System.Text.Json; namespace Ocelot.IntegrationTests; @@ -112,7 +112,7 @@ private async Task GivenIHaveAnOcelotToken(string adminPath) var response = await _httpClient.PostAsync(tokenUrl, content); var responseContent = await response.Content.ReadAsStringAsync(); response.EnsureSuccessStatusCode(); - _token = JsonSerializer.Deserialize(responseContent, JsonSerializerOptionsExtensions.Web); + _token = JsonSerializer.Deserialize(responseContent, JsonSerializerOptionsFactory.Web); var configPath = $"{adminPath}/.well-known/openid-configuration"; response = await _httpClient.GetAsync(configPath); response.EnsureSuccessStatusCode(); @@ -162,7 +162,7 @@ private static void GivenThereIsAConfiguration(FileConfiguration fileConfigurati // TODO: Turn method as async var configurationPath = $"{Directory.GetCurrentDirectory()}/ocelot.json"; - var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsExtensions.Web); + var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsFactory.Web); if (File.Exists(configurationPath)) { diff --git a/test/Ocelot.IntegrationTests/HeaderTests.cs b/test/Ocelot.IntegrationTests/HeaderTests.cs index 1972f3393..963f4fc55 100644 --- a/test/Ocelot.IntegrationTests/HeaderTests.cs +++ b/test/Ocelot.IntegrationTests/HeaderTests.cs @@ -3,10 +3,10 @@ using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Ocelot.Configuration.File; -using Ocelot.DependencyInjection; +using Ocelot.DependencyInjection; using Ocelot.Infrastructure; using Ocelot.Middleware; -using System.Net; +using System.Net; using System.Text.Json; [assembly: CollectionBehavior(DisableTestParallelization = true)] @@ -123,7 +123,7 @@ private static void GivenThereIsAConfiguration(FileConfiguration fileConfigurati { var configurationPath = $"{Directory.GetCurrentDirectory()}/ocelot.json"; - var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsExtensions.Web); + var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsFactory.Web); if (File.Exists(configurationPath)) { diff --git a/test/Ocelot.IntegrationTests/ThreadSafeHeadersTests.cs b/test/Ocelot.IntegrationTests/ThreadSafeHeadersTests.cs index 4f9db3b90..bb638d821 100644 --- a/test/Ocelot.IntegrationTests/ThreadSafeHeadersTests.cs +++ b/test/Ocelot.IntegrationTests/ThreadSafeHeadersTests.cs @@ -119,7 +119,7 @@ private static void GivenThereIsAConfiguration(FileConfiguration fileConfigurati { var configurationPath = $"{Directory.GetCurrentDirectory()}/ocelot.json"; - var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsExtensions.Web); + var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsFactory.Web); if (File.Exists(configurationPath)) { diff --git a/test/Ocelot.ManualTest/CustomOcelotMiddleware.cs b/test/Ocelot.ManualTest/CustomOcelotMiddleware.cs index cf5f70163..c55100e08 100644 --- a/test/Ocelot.ManualTest/CustomOcelotMiddleware.cs +++ b/test/Ocelot.ManualTest/CustomOcelotMiddleware.cs @@ -17,7 +17,7 @@ public static Task Invoke(HttpContext context, Func next) { logger.LogInformation(() => { - var metadataInJson = JsonSerializer.Serialize(metadata, JsonSerializerOptionsExtensions.Web); + var metadataInJson = JsonSerializer.Serialize(metadata, JsonSerializerOptionsFactory.Web); var message = $"My custom middleware found some metadata: {metadataInJson}"; return message; }); diff --git a/test/Ocelot.UnitTests/Configuration/DiskFileConfigurationRepositoryTests.cs b/test/Ocelot.UnitTests/Configuration/DiskFileConfigurationRepositoryTests.cs index c95a391fe..2ab45ac91 100644 --- a/test/Ocelot.UnitTests/Configuration/DiskFileConfigurationRepositoryTests.cs +++ b/test/Ocelot.UnitTests/Configuration/DiskFileConfigurationRepositoryTests.cs @@ -2,9 +2,9 @@ using Ocelot.Configuration.ChangeTracking; using Ocelot.Configuration.File; using Ocelot.Configuration.Repository; -using Ocelot.DependencyInjection; +using Ocelot.DependencyInjection; using Ocelot.Infrastructure; -using System.Runtime.CompilerServices; +using System.Runtime.CompilerServices; using System.Text.Json; namespace Ocelot.UnitTests.Configuration; @@ -157,14 +157,14 @@ private void ThenTheConfigurationIsStoredAs(FileConfiguration expecteds) private static void ThenTheOcelotJsonIsStoredAs(FileInfo ocelotJson, FileConfiguration expecteds) { var actual = File.ReadAllText(ocelotJson.FullName); - var expectedText = JsonSerializer.Serialize(expecteds, JsonSerializerOptionsExtensions.WebWriteIndented); + var expectedText = JsonSerializer.Serialize(expecteds, JsonSerializerOptionsFactory.WebWriteIndented); actual.ShouldBe(expectedText); } private void GivenTheConfigurationIs(FileConfiguration fileConfiguration, [CallerMemberName] string environmentName = null) { var environmentSpecificPath = Path.Combine(TestID, string.Format(ConfigurationBuilderExtensions.EnvironmentConfigFile, environmentName)); - var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsExtensions.WebWriteIndented); + var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsFactory.WebWriteIndented); var environmentSpecific = new FileInfo(environmentSpecificPath); if (environmentSpecific.Exists) { @@ -179,7 +179,7 @@ private void ThenTheConfigurationJsonIsIndented(FileConfiguration expecteds, [Ca { var environmentSpecific = Path.Combine(TestID, string.Format(ConfigurationBuilderExtensions.EnvironmentConfigFile, environmentName)); var actual = File.ReadAllText(environmentSpecific); - var expectedText = JsonSerializer.Serialize(expecteds, JsonSerializerOptionsExtensions.WebWriteIndented); + var expectedText = JsonSerializer.Serialize(expecteds, JsonSerializerOptionsFactory.WebWriteIndented); actual.ShouldBe(expectedText); _files.Add(environmentSpecific); } diff --git a/test/Ocelot.UnitTests/Consul/ConsulFileConfigurationRepositoryTests.cs b/test/Ocelot.UnitTests/Consul/ConsulFileConfigurationRepositoryTests.cs index 038c8e22e..b8b5bf5c5 100644 --- a/test/Ocelot.UnitTests/Consul/ConsulFileConfigurationRepositoryTests.cs +++ b/test/Ocelot.UnitTests/Consul/ConsulFileConfigurationRepositoryTests.cs @@ -1,13 +1,13 @@ using Consul; using Microsoft.Extensions.Options; using Ocelot.Cache; -using Ocelot.Configuration.File; +using Ocelot.Configuration.File; using Ocelot.Infrastructure; using Ocelot.Logging; using Ocelot.Provider.Consul; using Ocelot.Provider.Consul.Interfaces; using Ocelot.Responses; -using System.Text; +using System.Text; using System.Text.Json; namespace Ocelot.UnitTests.Consul; @@ -142,8 +142,8 @@ private void GivenTheConfigKeyComesFromFileConfig(string key) private void ThenTheConfigurationIs(FileConfiguration config) { - var expected = JsonSerializer.Serialize(config, JsonSerializerOptionsExtensions.WebWriteIndented); - var result = JsonSerializer.Serialize(_getResult.Data, JsonSerializerOptionsExtensions.WebWriteIndented); + var expected = JsonSerializer.Serialize(config, JsonSerializerOptionsFactory.WebWriteIndented); + var result = JsonSerializer.Serialize(_getResult.Data, JsonSerializerOptionsFactory.WebWriteIndented); result.ShouldBe(expected); } @@ -170,7 +170,7 @@ private void GivenFetchFromConsulReturnsNull() private void GivenFetchFromConsulSucceeds() { - var json = JsonSerializer.Serialize(_fileConfiguration, JsonSerializerOptionsExtensions.WebWriteIndented); + var json = JsonSerializer.Serialize(_fileConfiguration, JsonSerializerOptionsFactory.WebWriteIndented); var bytes = Encoding.UTF8.GetBytes(json); var kvp = new KVPair("OcelotConfiguration") { @@ -186,7 +186,7 @@ private void GivenFetchFromConsulSucceeds() private void ThenTheConfigurationIsStoredAs(FileConfiguration config) { - var json = JsonSerializer.Serialize(config, JsonSerializerOptionsExtensions.WebWriteIndented); + var json = JsonSerializer.Serialize(config, JsonSerializerOptionsFactory.WebWriteIndented); var bytes = Encoding.UTF8.GetBytes(json); _kvEndpoint.Verify(x => x.Put(It.Is(k => k.Value.SequenceEqual(bytes)), It.IsAny()), Times.Once); } diff --git a/test/Ocelot.UnitTests/Consul/ConsulTests.cs b/test/Ocelot.UnitTests/Consul/ConsulTests.cs index 97006ef3a..c3f1d14c4 100644 --- a/test/Ocelot.UnitTests/Consul/ConsulTests.cs +++ b/test/Ocelot.UnitTests/Consul/ConsulTests.cs @@ -205,7 +205,7 @@ private void GivenThereIsAFakeConsulServiceDiscoveryProvider([CallerMemberName] _receivedToken = values.First(); } - var json = JsonSerializer.Serialize(_consulServiceEntries, JsonSerializerOptionsExtensions.Web); + var json = JsonSerializer.Serialize(_consulServiceEntries, JsonSerializerOptionsFactory.Web); context.Response.Headers.Append("Content-Type", "application/json"); await context.Response.WriteAsync(json); } diff --git a/test/Ocelot.UnitTests/DependencyInjection/ConfigurationBuilderExtensionsTests.cs b/test/Ocelot.UnitTests/DependencyInjection/ConfigurationBuilderExtensionsTests.cs index 389487bcb..4736f268b 100644 --- a/test/Ocelot.UnitTests/DependencyInjection/ConfigurationBuilderExtensionsTests.cs +++ b/test/Ocelot.UnitTests/DependencyInjection/ConfigurationBuilderExtensionsTests.cs @@ -189,7 +189,7 @@ private void GivenMultipleConfigurationFiles(string folder, bool withEnvironment foreach (var part in configParts) { var filename = Path.Combine(folder, string.Format(ConfigurationBuilderExtensions.EnvironmentConfigFile, part.Key)); - File.WriteAllText(filename, JsonSerializer.Serialize(part.Value, JsonSerializerOptionsExtensions.WebWriteIndented)); + File.WriteAllText(filename, JsonSerializer.Serialize(part.Value, JsonSerializerOptionsFactory.WebWriteIndented)); _files.Add(filename); } } diff --git a/test/Ocelot.UnitTests/Kubernetes/KubeTests.cs b/test/Ocelot.UnitTests/Kubernetes/KubeTests.cs index 56b49f5a8..51d2f18fb 100644 --- a/test/Ocelot.UnitTests/Kubernetes/KubeTests.cs +++ b/test/Ocelot.UnitTests/Kubernetes/KubeTests.cs @@ -161,7 +161,7 @@ Task ProcessKubernetesRequest(HttpContext context) token = values.First(); } - var json = JsonSerializer.Serialize(_endpointEntries, JsonSerializerOptionsExtensions.Web); + var json = JsonSerializer.Serialize(_endpointEntries, JsonSerializerOptionsFactory.Web); context.Response.Headers.Append("Content-Type", "application/json"); return context.Response.WriteAsync(json); } From 147271c8c45346ca085fc5ad04142225acfb6f91 Mon Sep 17 00:00:00 2001 From: Mohammad Amin Pourmoradian <46063083+MohammadAminPourmoradian@users.noreply.github.com> Date: Sun, 28 Jul 2024 14:50:05 +0330 Subject: [PATCH 17/26] fix: remove unused JsonDocument object --- src/Ocelot/Multiplexer/MultiplexingMiddleware.cs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/Ocelot/Multiplexer/MultiplexingMiddleware.cs b/src/Ocelot/Multiplexer/MultiplexingMiddleware.cs index 281f14f58..76f2a4f6a 100644 --- a/src/Ocelot/Multiplexer/MultiplexingMiddleware.cs +++ b/src/Ocelot/Multiplexer/MultiplexingMiddleware.cs @@ -7,7 +7,6 @@ using Ocelot.Logging; using Ocelot.Middleware; using System.Collections; -using System.Text.Json; using System.Text.Json.Nodes; using Route = Ocelot.Configuration.Route; @@ -134,7 +133,6 @@ protected virtual async Task ProcessRoutesWithRouteKeysAsync(Http { var processing = new List>(); var content = await mainResponse.Items.DownstreamResponse().Content.ReadAsStringAsync(); - var jObject = JsonDocument.Parse(content); var jNode = JsonNode.Parse(content); foreach (var downstreamRoute in routes.Skip(1)) @@ -142,7 +140,7 @@ protected virtual async Task ProcessRoutesWithRouteKeysAsync(Http var matchAdvancedAgg = routeKeysConfigs.FirstOrDefault(q => q.RouteKey == downstreamRoute.Key); if (matchAdvancedAgg != null) { - processing.AddRange(ProcessRouteWithComplexAggregation(matchAdvancedAgg, jNode, jObject, context, downstreamRoute)); + processing.AddRange(ProcessRouteWithComplexAggregation(matchAdvancedAgg, jNode, context, downstreamRoute)); continue; } @@ -166,7 +164,7 @@ private Task MapResponsesAsync(HttpContext context, Route route, HttpContext mai /// Processing a route with aggregation. /// private IEnumerable> ProcessRouteWithComplexAggregation(AggregateRouteConfig matchAdvancedAgg, - JsonNode jNode, JsonDocument jObject, HttpContext httpContext, DownstreamRoute downstreamRoute) + JsonNode jNode, HttpContext httpContext, DownstreamRoute downstreamRoute) { var processing = new List>(); From b65a6d69d827687add3b0810fffe8a575867ffa4 Mon Sep 17 00:00:00 2001 From: Mohsen Rajabi Date: Thu, 3 Oct 2024 14:43:16 +0330 Subject: [PATCH 18/26] add --- .../Multiplexer/MultiplexingMiddleware.cs | 118 +++++++++++++++--- 1 file changed, 102 insertions(+), 16 deletions(-) diff --git a/src/Ocelot/Multiplexer/MultiplexingMiddleware.cs b/src/Ocelot/Multiplexer/MultiplexingMiddleware.cs index 76f2a4f6a..ee7a59cf3 100644 --- a/src/Ocelot/Multiplexer/MultiplexingMiddleware.cs +++ b/src/Ocelot/Multiplexer/MultiplexingMiddleware.cs @@ -1,5 +1,4 @@ -using Json.Path; -using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Primitives; using Ocelot.Configuration; using Ocelot.Configuration.File; @@ -7,7 +6,7 @@ using Ocelot.Logging; using Ocelot.Middleware; using System.Collections; -using System.Text.Json.Nodes; +using System.Text.Json; using Route = Ocelot.Configuration.Route; namespace Ocelot.Multiplexer; @@ -132,15 +131,15 @@ private async Task ProcessMainRouteAsync(HttpContext context, Downs protected virtual async Task ProcessRoutesWithRouteKeysAsync(HttpContext context, IEnumerable routes, IReadOnlyCollection routeKeysConfigs, HttpContext mainResponse) { var processing = new List>(); - var content = await mainResponse.Items.DownstreamResponse().Content.ReadAsStringAsync(); - var jNode = JsonNode.Parse(content); - + var content = await mainResponse.Items.DownstreamResponse().Content.ReadAsStringAsync(); + + foreach (var downstreamRoute in routes.Skip(1)) { var matchAdvancedAgg = routeKeysConfigs.FirstOrDefault(q => q.RouteKey == downstreamRoute.Key); if (matchAdvancedAgg != null) { - processing.AddRange(ProcessRouteWithComplexAggregation(matchAdvancedAgg, jNode, context, downstreamRoute)); + processing.AddRange(ProcessRouteWithComplexAggregation(matchAdvancedAgg, content, context, downstreamRoute)); continue; } @@ -163,17 +162,14 @@ private Task MapResponsesAsync(HttpContext context, Route route, HttpContext mai /// /// Processing a route with aggregation. /// - private IEnumerable> ProcessRouteWithComplexAggregation(AggregateRouteConfig matchAdvancedAgg, - JsonNode jNode, HttpContext httpContext, DownstreamRoute downstreamRoute) + private IEnumerable> ProcessRouteWithComplexAggregation(AggregateRouteConfig matchAdvancedAgg + , string content + , HttpContext httpContext, DownstreamRoute downstreamRoute) { var processing = new List>(); - var tokenPaths = JsonPath.Parse(matchAdvancedAgg.JsonPath); - var values = tokenPaths.Evaluate(jNode) - .Matches - .Select(s => s.Value?.ToString()) - .Distinct(); - + var values = ExtractValuesFromJsonPath(content, matchAdvancedAgg.JsonPath).Distinct(); + foreach (var value in values) { var tPnv = httpContext.Items.TemplatePlaceholderNameAndValues(); @@ -182,7 +178,97 @@ private IEnumerable> ProcessRouteWithComplexAggregation(Aggreg } return processing; - } + } + + //public static IEnumerable ExtractValuesFromJsonPath(string jsonContent, string jsonPath) + //{ + // using (JsonDocument document = JsonDocument.Parse(jsonContent)) + // { + // var root = document.RootElement; + + // // حذف '$' از مسیر و تقسیم آن بر اساس '.' + // var pathParts = jsonPath.Trim('$', '.').Split('.'); + + // var elements = new List(); + + // // فراخوانی تابع بازگشتی برای پیمایش مسیر + // TraverseJsonPath(root, pathParts, 0, elements); + + // return elements; + // } + //} + + //// تابع بازگشتی برای پیمایش مسیر JSONPath + //public static void TraverseJsonPath(JsonElement currentElement, string[] pathParts, int index, List elements) + //{ + // if (index >= pathParts.Length) return; // در صورت اتمام مسیر، از تابع خارج می‌شویم + + // var part = pathParts[index]; + + // if (currentElement.ValueKind == JsonValueKind.Array) + // { + // // اگر آرایه باشد، برای هر عنصر در آرایه پیمایش می‌کنیم + // foreach (var element in currentElement.EnumerateArray()) + // { + // TraverseJsonPath(element, pathParts, index + 1, elements); + // } + // } + // else if (currentElement.ValueKind == JsonValueKind.Object) + // { + // // اگر شیء باشد، ویژگی مورد نظر را می‌یابیم + // if (currentElement.TryGetProperty(part, out JsonElement nextElement)) + // { + // TraverseJsonPath(nextElement, pathParts, index + 1, elements); + // } + // } + // else + // { + // // اگر عنصر از نوع دیگری باشد (مثلاً رشته یا عدد)، به نتیجه اضافه می‌کنیم + // elements.Add(currentElement.ToString()); + // } + //} + + public static IEnumerable ExtractValuesFromJsonPathOld(string jsonContent, string jsonPath) + { + using (JsonDocument document = JsonDocument.Parse(jsonContent)) + { + var root = document.RootElement; + + var pathParts = jsonPath.Trim('$', '.').Split('.'); + + var elements = new List(); + + foreach (var part in pathParts) + { + if (root.ValueKind == JsonValueKind.Array) + { + foreach (var element in root.EnumerateArray()) + { + if (element.ValueKind == JsonValueKind.Object) + { + if (element.TryGetProperty(part, out JsonElement property)) + { + elements.Add(property.ToString()); + } + } + } + } + else + { + if (root.TryGetProperty(part, out JsonElement nextElement)) + { + elements.Add(nextElement.ToString()); + } + else + { + return Enumerable.Empty(); + } + } + } + + return elements; + } + } /// /// Process a downstream route asynchronously. From 0fda6afd26c6935bcc597738b2ce648eaf6721fc Mon Sep 17 00:00:00 2001 From: Mohsen Rajabi Date: Fri, 4 Oct 2024 00:18:26 +0330 Subject: [PATCH 19/26] fix: rm JsonPath.Net --- .../JsonSerializerOptionsFactory.cs | 73 ++++++++++++ .../Multiplexer/MultiplexingMiddleware.cs | 107 ++---------------- src/Ocelot/Ocelot.csproj | 1 - .../JsonSerializerOptionsFactoryTests.cs | 56 +++++++++ 4 files changed, 139 insertions(+), 98 deletions(-) create mode 100644 test/Ocelot.UnitTests/JsonSerializerOptionsFactoryTests.cs diff --git a/src/Ocelot/Infrastructure/JsonSerializerOptionsFactory.cs b/src/Ocelot/Infrastructure/JsonSerializerOptionsFactory.cs index 1434b21eb..adf12d781 100644 --- a/src/Ocelot/Infrastructure/JsonSerializerOptionsFactory.cs +++ b/src/Ocelot/Infrastructure/JsonSerializerOptionsFactory.cs @@ -24,4 +24,77 @@ public static class JsonSerializerOptionsFactory ReferenceHandler = ReferenceHandler.IgnoreCycles, WriteIndented = true }; + + public static List ExtractValuesFromJsonPath(this JsonDocument document, string jsonPath) + { + var root = document.RootElement; + + var pathParts = jsonPath.Trim('$', '.').Replace("[*]", "").Trim().Split('.'); + + var elements = new List(); + + TraverseJsonPath(root, pathParts, 0, elements); + + return elements; + } + + private static void TraverseJsonPath(JsonElement currentElement, string[] pathParts, int index, List elements) + { + if (index >= pathParts.Length) return; + + var part = pathParts[index]; + + if (currentElement.ValueKind == JsonValueKind.Array) + { + foreach (var element in currentElement.EnumerateArray()) + { + if (element.ValueKind == JsonValueKind.Object) + { + if (element.TryGetProperty(part, out JsonElement nextElement)) + { + if (nextElement.ValueKind == JsonValueKind.Array) + { + TraverseJsonPath(nextElement, pathParts, 0, elements); + } + else + { + var item = nextElement.ToString(); + if (!string.IsNullOrWhiteSpace(item)) + elements.Add(item); + } + } + else + { + TraverseJsonPath(element, pathParts, index + 1, elements); + } + } + else + { + TraverseJsonPath(element, pathParts, index + 1, elements); + } + } + } + else if (currentElement.ValueKind == JsonValueKind.Object) + { + if (currentElement.TryGetProperty(part, out JsonElement nextElement)) + { + if (nextElement.ValueKind == JsonValueKind.Array) + { + TraverseJsonPath(nextElement, pathParts, index + 1, elements); + } + else + { + var item = nextElement.ToString(); + if (!string.IsNullOrWhiteSpace(item)) + elements.Add(item); + } + } + } + else + { + var item = currentElement.ToString(); + if (!string.IsNullOrWhiteSpace(item)) + elements.Add(item); + } + } } diff --git a/src/Ocelot/Multiplexer/MultiplexingMiddleware.cs b/src/Ocelot/Multiplexer/MultiplexingMiddleware.cs index ee7a59cf3..5c20594ca 100644 --- a/src/Ocelot/Multiplexer/MultiplexingMiddleware.cs +++ b/src/Ocelot/Multiplexer/MultiplexingMiddleware.cs @@ -3,6 +3,7 @@ using Ocelot.Configuration; using Ocelot.Configuration.File; using Ocelot.DownstreamRouteFinder.UrlMatcher; +using Ocelot.Infrastructure; using Ocelot.Logging; using Ocelot.Middleware; using System.Collections; @@ -131,15 +132,15 @@ private async Task ProcessMainRouteAsync(HttpContext context, Downs protected virtual async Task ProcessRoutesWithRouteKeysAsync(HttpContext context, IEnumerable routes, IReadOnlyCollection routeKeysConfigs, HttpContext mainResponse) { var processing = new List>(); - var content = await mainResponse.Items.DownstreamResponse().Content.ReadAsStringAsync(); - + var content = await mainResponse.Items.DownstreamResponse().Content.ReadAsStringAsync(); + using var document = JsonDocument.Parse(content); foreach (var downstreamRoute in routes.Skip(1)) { var matchAdvancedAgg = routeKeysConfigs.FirstOrDefault(q => q.RouteKey == downstreamRoute.Key); if (matchAdvancedAgg != null) { - processing.AddRange(ProcessRouteWithComplexAggregation(matchAdvancedAgg, content, context, downstreamRoute)); + processing.AddRange(ProcessRouteWithComplexAggregation(matchAdvancedAgg, document, context, downstreamRoute)); continue; } @@ -162,13 +163,13 @@ private Task MapResponsesAsync(HttpContext context, Route route, HttpContext mai /// /// Processing a route with aggregation. /// - private IEnumerable> ProcessRouteWithComplexAggregation(AggregateRouteConfig matchAdvancedAgg - , string content - , HttpContext httpContext, DownstreamRoute downstreamRoute) + private IEnumerable> ProcessRouteWithComplexAggregation(AggregateRouteConfig matchAdvancedAgg, + JsonDocument document, HttpContext httpContext, DownstreamRoute downstreamRoute) { var processing = new List>(); - var values = ExtractValuesFromJsonPath(content, matchAdvancedAgg.JsonPath).Distinct(); + var values = document.ExtractValuesFromJsonPath(matchAdvancedAgg.JsonPath) + .Distinct(); foreach (var value in values) { @@ -180,96 +181,8 @@ private IEnumerable> ProcessRouteWithComplexAggregation(Aggreg return processing; } - //public static IEnumerable ExtractValuesFromJsonPath(string jsonContent, string jsonPath) - //{ - // using (JsonDocument document = JsonDocument.Parse(jsonContent)) - // { - // var root = document.RootElement; - - // // حذف '$' از مسیر و تقسیم آن بر اساس '.' - // var pathParts = jsonPath.Trim('$', '.').Split('.'); - - // var elements = new List(); - - // // فراخوانی تابع بازگشتی برای پیمایش مسیر - // TraverseJsonPath(root, pathParts, 0, elements); - - // return elements; - // } - //} - - //// تابع بازگشتی برای پیمایش مسیر JSONPath - //public static void TraverseJsonPath(JsonElement currentElement, string[] pathParts, int index, List elements) - //{ - // if (index >= pathParts.Length) return; // در صورت اتمام مسیر، از تابع خارج می‌شویم - - // var part = pathParts[index]; - - // if (currentElement.ValueKind == JsonValueKind.Array) - // { - // // اگر آرایه باشد، برای هر عنصر در آرایه پیمایش می‌کنیم - // foreach (var element in currentElement.EnumerateArray()) - // { - // TraverseJsonPath(element, pathParts, index + 1, elements); - // } - // } - // else if (currentElement.ValueKind == JsonValueKind.Object) - // { - // // اگر شیء باشد، ویژگی مورد نظر را می‌یابیم - // if (currentElement.TryGetProperty(part, out JsonElement nextElement)) - // { - // TraverseJsonPath(nextElement, pathParts, index + 1, elements); - // } - // } - // else - // { - // // اگر عنصر از نوع دیگری باشد (مثلاً رشته یا عدد)، به نتیجه اضافه می‌کنیم - // elements.Add(currentElement.ToString()); - // } - //} - - public static IEnumerable ExtractValuesFromJsonPathOld(string jsonContent, string jsonPath) - { - using (JsonDocument document = JsonDocument.Parse(jsonContent)) - { - var root = document.RootElement; - - var pathParts = jsonPath.Trim('$', '.').Split('.'); - - var elements = new List(); - - foreach (var part in pathParts) - { - if (root.ValueKind == JsonValueKind.Array) - { - foreach (var element in root.EnumerateArray()) - { - if (element.ValueKind == JsonValueKind.Object) - { - if (element.TryGetProperty(part, out JsonElement property)) - { - elements.Add(property.ToString()); - } - } - } - } - else - { - if (root.TryGetProperty(part, out JsonElement nextElement)) - { - elements.Add(nextElement.ToString()); - } - else - { - return Enumerable.Empty(); - } - } - } - - return elements; - } - } - + + /// /// Process a downstream route asynchronously. /// diff --git a/src/Ocelot/Ocelot.csproj b/src/Ocelot/Ocelot.csproj index 742f5da90..bc9bd93fc 100644 --- a/src/Ocelot/Ocelot.csproj +++ b/src/Ocelot/Ocelot.csproj @@ -32,7 +32,6 @@ - NU1701 diff --git a/test/Ocelot.UnitTests/JsonSerializerOptionsFactoryTests.cs b/test/Ocelot.UnitTests/JsonSerializerOptionsFactoryTests.cs new file mode 100644 index 000000000..d389745bd --- /dev/null +++ b/test/Ocelot.UnitTests/JsonSerializerOptionsFactoryTests.cs @@ -0,0 +1,56 @@ +using Ocelot.Infrastructure; +using System.Text.Json; + +namespace Ocelot.UnitTests +{ + public class JsonSerializerOptionsFactoryTests : UnitTest + { + [Fact] + public void should_json_path() + { + //Arrange + var json = + "[{\"id\":1,\"writerId\":1,\"postId\":2,\"text\":\"text1\"},{\"id\":2,\"writerId\":1,\"postId\":2,\"text\":\"text2\"}]"; + var path = "$[*].writerId"; + var document = JsonDocument.Parse(json); + + //Act + var result = document.ExtractValuesFromJsonPath(path); + + //Assert + result.ShouldBeEquivalentTo(new List { "1", "1" }); + } + + [Fact] + public void should_json_path_nested() + { + //Arrange + var json = + "[{\"id\":1,\"writerId\":1,\"postId\":2,\"text\":\"text1\",\"comments\":[{\"commentId\":1,\"text\":\"Good post!\"},{\"commentId\":2,\"text\":\"Nice post!\"}]},{\"id\":2,\"writerId\":2,\"postId\":2,\"text\":\"text2\",\"comments\":[{\"commentId\":3,\"text\":\"Interesting.\"}]}]"; + var path = "$[*].comments[*].text"; + var document = JsonDocument.Parse(json); + + //Act + var result = document.ExtractValuesFromJsonPath(path); + + //Assert + result.ShouldBeEquivalentTo(new List { "Good post!", "Nice post!", "Interesting." }); + } + + [Fact] + public void should_json_path_nested_null() + { + //Arrange + var json = + "[{\"id\":1,\"writerId\":1,\"postId\":2,\"text\":\"text1\",\"comments\":[{\"commentId\":1,\"text\":null},{\"commentId\":2,\"text\":\"Nice post!\"}]},{\"id\":2,\"writerId\":2,\"postId\":2,\"text\":\"text2\",\"comments\":[{\"commentId\":3,\"text\":\"Interesting.\"}]}]"; + var path = "$[*].comments[*].text"; + var document = JsonDocument.Parse(json); + + //Act + var result = document.ExtractValuesFromJsonPath(path); + + //Assert + result.ShouldBeEquivalentTo(new List { "Nice post!", "Interesting." }); + } + } +} From 4863b2e642f50a76e0c026e6ca17a5dbca4f573a Mon Sep 17 00:00:00 2001 From: Mohsen Rajabi Date: Fri, 4 Oct 2024 10:01:01 +0330 Subject: [PATCH 20/26] fix: add more test --- .../JsonSerializerOptionsFactoryTests.cs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/test/Ocelot.UnitTests/JsonSerializerOptionsFactoryTests.cs b/test/Ocelot.UnitTests/JsonSerializerOptionsFactoryTests.cs index d389745bd..81fd97d95 100644 --- a/test/Ocelot.UnitTests/JsonSerializerOptionsFactoryTests.cs +++ b/test/Ocelot.UnitTests/JsonSerializerOptionsFactoryTests.cs @@ -7,6 +7,21 @@ public class JsonSerializerOptionsFactoryTests : UnitTest { [Fact] public void should_json_path() + { + //Arrange + var json = "{\"id\":1,\"writerId\":1,\"postId\":2,\"text\":\"text1\"}"; + var path = "$writerId"; + var document = JsonDocument.Parse(json); + + //Act + var result = document.ExtractValuesFromJsonPath(path); + + //Assert + result.ShouldBeEquivalentTo(new List { "1" }); + } + + [Fact] + public void should_json_path_array() { //Arrange var json = From dea5e3728f62e2d7549932f4a85c3ea6f1556936 Mon Sep 17 00:00:00 2001 From: Raman Maksimchuk Date: Sat, 2 Nov 2024 17:35:37 +0300 Subject: [PATCH 21/26] Fix errors and warnings --- src/Ocelot/DependencyInjection/OcelotBuilder.cs | 2 -- .../JsonSerializerOptionsFactory.cs | 15 ++++++++++++--- src/Ocelot/Multiplexer/MultiplexingMiddleware.cs | 2 -- src/Ocelot/RateLimiting/RateLimitCounter.cs | 4 +--- .../Configuration/ConfigurationInConsulTests.cs | 5 +++-- .../ConsulConfigurationInConsulTests.cs | 1 + .../ServiceDiscovery/ConsulWebSocketTests.cs | 2 +- test/Ocelot.IntegrationTests/BearerToken.cs | 1 + test/Ocelot.UnitTests/Kubernetes/KubeTests.cs | 2 +- 9 files changed, 20 insertions(+), 14 deletions(-) diff --git a/src/Ocelot/DependencyInjection/OcelotBuilder.cs b/src/Ocelot/DependencyInjection/OcelotBuilder.cs index aa1dec8f7..e73719011 100644 --- a/src/Ocelot/DependencyInjection/OcelotBuilder.cs +++ b/src/Ocelot/DependencyInjection/OcelotBuilder.cs @@ -155,7 +155,6 @@ public OcelotBuilder(IServiceCollection services, IConfiguration configurationRo /// /// Adds default ASP.NET services which are the minimal part of the gateway core. /// - /// Finally the builder adds Newtonsoft.Json services via the extension-method.
/// To remove these services, use custom builder in the extension-method. ///
///
@@ -170,7 +169,6 @@ public OcelotBuilder(IServiceCollection services, IConfiguration configurationRo /// -
/// -
/// -
- /// - , removable. /// /// /// The default builder being returned by extension-method. diff --git a/src/Ocelot/Infrastructure/JsonSerializerOptionsFactory.cs b/src/Ocelot/Infrastructure/JsonSerializerOptionsFactory.cs index adf12d781..4cd4b695a 100644 --- a/src/Ocelot/Infrastructure/JsonSerializerOptionsFactory.cs +++ b/src/Ocelot/Infrastructure/JsonSerializerOptionsFactory.cs @@ -13,7 +13,7 @@ public static class JsonSerializerOptionsFactory NumberHandling = JsonNumberHandling.AllowReadingFromString, PropertyNameCaseInsensitive = true, ReferenceHandler = ReferenceHandler.IgnoreCycles, - WriteIndented = false + WriteIndented = false, }; public static readonly JsonSerializerOptions WebWriteIndented = new() @@ -22,7 +22,7 @@ public static class JsonSerializerOptionsFactory NumberHandling = JsonNumberHandling.AllowReadingFromString, PropertyNameCaseInsensitive = true, ReferenceHandler = ReferenceHandler.IgnoreCycles, - WriteIndented = true + WriteIndented = true, }; public static List ExtractValuesFromJsonPath(this JsonDocument document, string jsonPath) @@ -40,7 +40,10 @@ public static List ExtractValuesFromJsonPath(this JsonDocument document, private static void TraverseJsonPath(JsonElement currentElement, string[] pathParts, int index, List elements) { - if (index >= pathParts.Length) return; + if (index >= pathParts.Length) + { + return; + } var part = pathParts[index]; @@ -60,7 +63,9 @@ private static void TraverseJsonPath(JsonElement currentElement, string[] pathPa { var item = nextElement.ToString(); if (!string.IsNullOrWhiteSpace(item)) + { elements.Add(item); + } } } else @@ -86,7 +91,9 @@ private static void TraverseJsonPath(JsonElement currentElement, string[] pathPa { var item = nextElement.ToString(); if (!string.IsNullOrWhiteSpace(item)) + { elements.Add(item); + } } } } @@ -94,7 +101,9 @@ private static void TraverseJsonPath(JsonElement currentElement, string[] pathPa { var item = currentElement.ToString(); if (!string.IsNullOrWhiteSpace(item)) + { elements.Add(item); + } } } } diff --git a/src/Ocelot/Multiplexer/MultiplexingMiddleware.cs b/src/Ocelot/Multiplexer/MultiplexingMiddleware.cs index 5c20594ca..f5cce0d81 100644 --- a/src/Ocelot/Multiplexer/MultiplexingMiddleware.cs +++ b/src/Ocelot/Multiplexer/MultiplexingMiddleware.cs @@ -181,8 +181,6 @@ private IEnumerable> ProcessRouteWithComplexAggregation(Aggreg return processing; } - - /// /// Process a downstream route asynchronously. /// diff --git a/src/Ocelot/RateLimiting/RateLimitCounter.cs b/src/Ocelot/RateLimiting/RateLimitCounter.cs index 850911dfb..3bcbe78d6 100644 --- a/src/Ocelot/RateLimiting/RateLimitCounter.cs +++ b/src/Ocelot/RateLimiting/RateLimitCounter.cs @@ -1,6 +1,4 @@ - - -using System.Text.Json.Serialization; +using System.Text.Json.Serialization; namespace Ocelot.RateLimiting; diff --git a/test/Ocelot.AcceptanceTests/Configuration/ConfigurationInConsulTests.cs b/test/Ocelot.AcceptanceTests/Configuration/ConfigurationInConsulTests.cs index 3ec1d052b..f966fa1ed 100644 --- a/test/Ocelot.AcceptanceTests/Configuration/ConfigurationInConsulTests.cs +++ b/test/Ocelot.AcceptanceTests/Configuration/ConfigurationInConsulTests.cs @@ -11,6 +11,7 @@ using Ocelot.Cache.CacheManager; using Ocelot.Configuration.File; using Ocelot.DependencyInjection; +using Ocelot.Infrastructure; using Ocelot.Middleware; using Ocelot.Provider.Consul; using System.Text; @@ -150,9 +151,9 @@ private Task GivenThereIsAFakeConsulServiceDiscoveryProvider(string url, string // var json = reader.ReadToEnd(); var json = await reader.ReadToEndAsync(); - _config = JsonSerializer.Deserialize(json, JsonSerializerOptionsFactory.Web); + _config = JsonSerializer.Deserialize(json, JsonSerializerOptionsFactory.Web); - var response = JsonSerializer.Serialize(true, JsonSerializerOptionsFactory.Web); + var response = JsonSerializer.Serialize(true, JsonSerializerOptionsFactory.Web); await context.Response.WriteAsync(response); } diff --git a/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulConfigurationInConsulTests.cs b/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulConfigurationInConsulTests.cs index a90d46876..41c82f5bb 100644 --- a/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulConfigurationInConsulTests.cs +++ b/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulConfigurationInConsulTests.cs @@ -8,6 +8,7 @@ using Ocelot.Cache; using Ocelot.Configuration.File; using Ocelot.DependencyInjection; +using Ocelot.Infrastructure; using Ocelot.Middleware; using Ocelot.Provider.Consul; using System.Text; diff --git a/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulWebSocketTests.cs b/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulWebSocketTests.cs index eed86bb96..1f39471c4 100644 --- a/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulWebSocketTests.cs +++ b/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulWebSocketTests.cs @@ -5,9 +5,9 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; -using Newtonsoft.Json; using Ocelot.Configuration.File; using Ocelot.DependencyInjection; +using Ocelot.Infrastructure; using Ocelot.Middleware; using Ocelot.Provider.Consul; using Ocelot.WebSockets; diff --git a/test/Ocelot.IntegrationTests/BearerToken.cs b/test/Ocelot.IntegrationTests/BearerToken.cs index 7a4d7c712..10fc31575 100644 --- a/test/Ocelot.IntegrationTests/BearerToken.cs +++ b/test/Ocelot.IntegrationTests/BearerToken.cs @@ -1,3 +1,4 @@ +using System.Text.Json.Serialization; namespace Ocelot.IntegrationTests; diff --git a/test/Ocelot.UnitTests/Kubernetes/KubeTests.cs b/test/Ocelot.UnitTests/Kubernetes/KubeTests.cs index 51d2f18fb..83d427ade 100644 --- a/test/Ocelot.UnitTests/Kubernetes/KubeTests.cs +++ b/test/Ocelot.UnitTests/Kubernetes/KubeTests.cs @@ -161,7 +161,7 @@ Task ProcessKubernetesRequest(HttpContext context) token = values.First(); } - var json = JsonSerializer.Serialize(_endpointEntries, JsonSerializerOptionsFactory.Web); + var json = JsonSerializer.Serialize(endpointEntries, JsonSerializerOptionsFactory.Web); context.Response.Headers.Append("Content-Type", "application/json"); return context.Response.WriteAsync(json); } From 885ee5b4221264f62cc366b66f64c8e5c4982cb0 Mon Sep 17 00:00:00 2001 From: Raman Maksimchuk Date: Sat, 2 Nov 2024 17:48:26 +0300 Subject: [PATCH 22/26] Fix Ocelot.Benchmarks build --- .../JsonSerializerBenchmark.cs | 23 ++++++++----------- .../Ocelot.Benchmarks.csproj | 5 ++-- 2 files changed, 11 insertions(+), 17 deletions(-) diff --git a/test/Ocelot.Benchmarks/JsonSerializerBenchmark.cs b/test/Ocelot.Benchmarks/JsonSerializerBenchmark.cs index 35919a441..2bae5cfb0 100644 --- a/test/Ocelot.Benchmarks/JsonSerializerBenchmark.cs +++ b/test/Ocelot.Benchmarks/JsonSerializerBenchmark.cs @@ -19,21 +19,16 @@ public class JsonSerializerBenchmark : ManualConfig [GlobalSetup] public void GlobalSetup() { - Faker faker = new Faker().CustomInstantiator( - f => - new User - { - UserId = Guid.NewGuid(), - FirstName = f.Name.FirstName(), - LastName = f.Name.LastName(), - FullName = f.Name.FullName(), - Username = f.Internet.UserName(f.Name.FirstName(), f.Name.LastName()), - Email = f.Internet.Email(f.Name.FirstName(), f.Name.LastName()) - } - ); - + Faker faker = new Faker().CustomInstantiator(f => new User + { + UserId = Guid.NewGuid(), + FirstName = f.Name.FirstName(), + LastName = f.Name.LastName(), + FullName = f.Name.FullName(), + Username = f.Internet.UserName(f.Name.FirstName(), f.Name.LastName()), + Email = f.Internet.Email(f.Name.FirstName(), f.Name.LastName()), + }); _testUsers = faker.Generate(Count); - _serializedTestUsers = JsonSerializer.Serialize(_testUsers); } diff --git a/test/Ocelot.Benchmarks/Ocelot.Benchmarks.csproj b/test/Ocelot.Benchmarks/Ocelot.Benchmarks.csproj index e4374e6f5..e18d87e72 100644 --- a/test/Ocelot.Benchmarks/Ocelot.Benchmarks.csproj +++ b/test/Ocelot.Benchmarks/Ocelot.Benchmarks.csproj @@ -25,13 +25,12 @@ - - + all - + From bd2da052c3aead8aa94028cee345fd00cc74f30b Mon Sep 17 00:00:00 2001 From: Mohsen Rajabi Date: Wed, 18 Dec 2024 23:36:48 +0330 Subject: [PATCH 23/26] fix: fix something --- .../DiskFileConfigurationRepository.cs | 8 +- .../Repository/FileConfigurationPoller.cs | 18 +-- .../ConfigurationBuilderExtensions.cs | 14 +- .../DependencyInjection/OcelotBuilder.cs | 6 +- .../EurekaServiceDiscoveryTests.cs | 46 +++---- .../JsonSerializerBenchmark.cs | 122 +++++++++--------- .../AdministrationTests.cs | 1 - .../JsonSerializerOptionsFactoryTests.cs | 106 +++++++-------- 8 files changed, 160 insertions(+), 161 deletions(-) diff --git a/src/Ocelot/Configuration/Repository/DiskFileConfigurationRepository.cs b/src/Ocelot/Configuration/Repository/DiskFileConfigurationRepository.cs index 7fd43a688..ad4abf8c2 100644 --- a/src/Ocelot/Configuration/Repository/DiskFileConfigurationRepository.cs +++ b/src/Ocelot/Configuration/Repository/DiskFileConfigurationRepository.cs @@ -50,14 +50,14 @@ public Task> Get() jsonConfiguration = FileSys.ReadAllText(_environmentFile.FullName); } - var fileConfiguration = JsonSerializer.Deserialize(jsonConfiguration, JsonSerializerOptionsFactory.Web); + var fileConfiguration = JsonSerializer.Deserialize(jsonConfiguration, JsonSerializerOptionsFactory.Web); return Task.FromResult>(new OkResponse(fileConfiguration)); } - public Task Set(FileConfiguration fileConfiguration) - { - var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsFactory.WebWriteIndented); + public Task Set(FileConfiguration fileConfiguration) + { + var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsFactory.WebWriteIndented); lock (_lock) { diff --git a/src/Ocelot/Configuration/Repository/FileConfigurationPoller.cs b/src/Ocelot/Configuration/Repository/FileConfigurationPoller.cs index abff81463..080f18fff 100644 --- a/src/Ocelot/Configuration/Repository/FileConfigurationPoller.cs +++ b/src/Ocelot/Configuration/Repository/FileConfigurationPoller.cs @@ -90,15 +90,15 @@ private async Task Poll() _logger.LogInformation("Finished polling"); } - /// - /// We could do object comparison here but performance isnt really a problem. This might be an issue one day!. - /// - /// hash of the config. - private static string ToJson(FileConfiguration config) - { - var currentHash = JsonSerializer.Serialize(config, JsonSerializerOptionsFactory.Web); - return currentHash; - } + /// + /// We could do object comparison here but performance isnt really a problem. This might be an issue one day!. + /// + /// hash of the config. + private static string ToJson(FileConfiguration config) + { + var currentHash = JsonSerializer.Serialize(config, JsonSerializerOptionsFactory.Web); + return currentHash; + } public void Dispose() { diff --git a/src/Ocelot/DependencyInjection/ConfigurationBuilderExtensions.cs b/src/Ocelot/DependencyInjection/ConfigurationBuilderExtensions.cs index 1e3915704..76955dee3 100644 --- a/src/Ocelot/DependencyInjection/ConfigurationBuilderExtensions.cs +++ b/src/Ocelot/DependencyInjection/ConfigurationBuilderExtensions.cs @@ -1,6 +1,6 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.Configuration.Memory; +using Microsoft.Extensions.Configuration.Memory; using Ocelot.Configuration.File; using Ocelot.Infrastructure; using System.Text; @@ -92,8 +92,8 @@ public static IConfigurationBuilder AddOcelot(this IConfigurationBuilder builder private static IConfigurationBuilder ApplyMergeOcelotJsonOption(IConfigurationBuilder builder, MergeOcelotJson mergeTo, string json, string primaryConfigFile, bool? optional, bool? reloadOnChange) { - return mergeTo == MergeOcelotJson.ToMemory ? - builder.AddJsonStream(new MemoryStream(Encoding.UTF8.GetBytes(json))) : + return mergeTo == MergeOcelotJson.ToMemory ? + builder.AddJsonStream(new MemoryStream(Encoding.UTF8.GetBytes(json))) : AddOcelotJsonFile(builder, json, primaryConfigFile, optional, reloadOnChange); } @@ -135,7 +135,7 @@ private static string GetMergedOcelotJson(string folder, IWebHostEnvironment env var lines = File.ReadAllText(file.FullName); var config = JsonSerializer.Deserialize(lines, JsonSerializerOptionsFactory.Web); - if (file.Name.Equals(globalFileInfo.Name, StringComparison.OrdinalIgnoreCase) && + if (file.Name.Equals(globalFileInfo.Name, StringComparison.OrdinalIgnoreCase) && file.FullName.Equals(globalFileInfo.FullName, StringComparison.OrdinalIgnoreCase)) { fileConfiguration.GlobalConfiguration = config.GlobalConfiguration; @@ -159,11 +159,11 @@ private static string GetMergedOcelotJson(string folder, IWebHostEnvironment env /// The 2nd argument of the AddJsonFile. /// The 3rd argument of the AddJsonFile. /// An object. - public static IConfigurationBuilder AddOcelot(this IConfigurationBuilder builder, FileConfiguration fileConfiguration, + public static IConfigurationBuilder AddOcelot(this IConfigurationBuilder builder, FileConfiguration fileConfiguration, string primaryConfigFile = null, bool? optional = null, bool? reloadOnChange = null) // optional injections { - var json = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsFactory.WebWriteIndented); - return AddOcelotJsonFile(builder, json, primaryConfigFile, optional, reloadOnChange); + var json = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsFactory.WebWriteIndented); + return AddOcelotJsonFile(builder, json, primaryConfigFile, optional, reloadOnChange); } /// diff --git a/src/Ocelot/DependencyInjection/OcelotBuilder.cs b/src/Ocelot/DependencyInjection/OcelotBuilder.cs index e73719011..b0a0c9c22 100644 --- a/src/Ocelot/DependencyInjection/OcelotBuilder.cs +++ b/src/Ocelot/DependencyInjection/OcelotBuilder.cs @@ -111,7 +111,7 @@ public OcelotBuilder(IServiceCollection services, IConfiguration configurationRo Services.TryAddSingleton(); Services.TryAddSingleton(); Services.TryAddSingleton(); - + Services.TryAddSingleton(); Services.TryAddSingleton, OcelotConfigurationMonitor>(); @@ -165,10 +165,10 @@ public OcelotBuilder(IServiceCollection services, IConfiguration configurationRo /// -
/// - . /// - /// Warning! The following extensions being called:
+ /// Warning! The following extensions being called
/// -
/// -
- /// -
+ /// - . ///
/// /// The default builder being returned by extension-method. diff --git a/test/Ocelot.AcceptanceTests/ServiceDiscovery/EurekaServiceDiscoveryTests.cs b/test/Ocelot.AcceptanceTests/ServiceDiscovery/EurekaServiceDiscoveryTests.cs index 484e71cff..c43669121 100644 --- a/test/Ocelot.AcceptanceTests/ServiceDiscovery/EurekaServiceDiscoveryTests.cs +++ b/test/Ocelot.AcceptanceTests/ServiceDiscovery/EurekaServiceDiscoveryTests.cs @@ -194,28 +194,28 @@ public FakeEurekaService(string serviceId, string host, int port, bool isSecure, public IDictionary Metadata { get; } } - public class Port - { - [JsonPropertyName("$")] - public int value { get; set; } +public class Port +{ + [JsonPropertyName("$")] + public int value { get; set; } - [JsonPropertyName("@enabled")] - public string enabled { get; set; } - } + [JsonPropertyName("@enabled")] + public string enabled { get; set; } +} - public class SecurePort - { - [JsonPropertyName("$")] - public int value { get; set; } +public class SecurePort +{ + [JsonPropertyName("$")] + public int value { get; set; } - [JsonPropertyName("@enabled")] - public string enabled { get; set; } - } + [JsonPropertyName("@enabled")] + public string enabled { get; set; } +} - public class DataCenterInfo - { - [JsonPropertyName("@class")] - public string value { get; set; } +public class DataCenterInfo +{ + [JsonPropertyName("@class")] + public string value { get; set; } public string name { get; set; } } @@ -235,11 +235,11 @@ public class LeaseInfo public long serviceUpTimestamp { get; set; } } - public class ValueMetadata - { - [JsonPropertyName("@class")] - public string value { get; set; } - } +public class ValueMetadata +{ + [JsonPropertyName("@class")] + public string value { get; set; } +} public class Instance { diff --git a/test/Ocelot.Benchmarks/JsonSerializerBenchmark.cs b/test/Ocelot.Benchmarks/JsonSerializerBenchmark.cs index 2bae5cfb0..046bb47a2 100644 --- a/test/Ocelot.Benchmarks/JsonSerializerBenchmark.cs +++ b/test/Ocelot.Benchmarks/JsonSerializerBenchmark.cs @@ -3,80 +3,80 @@ using Newtonsoft.Json; using JsonSerializer = System.Text.Json.JsonSerializer; -namespace Ocelot.Benchmarks +namespace Ocelot.Benchmarks; + +[SimpleJob(RuntimeMoniker.Net80)] +[Config(typeof(JsonSerializerBenchmark))] +public class JsonSerializerBenchmark : ManualConfig { - [SimpleJob(RuntimeMoniker.Net80)] - [Config(typeof(JsonSerializerBenchmark))] - public class JsonSerializerBenchmark : ManualConfig - { - private string _serializedTestUsers; + private string _serializedTestUsers; - private List _testUsers = new(); + private List _testUsers = new(); - [Params(1000)] - public int Count { get; set; } + [Params(1000)] + public int Count { get; set; } - [GlobalSetup] - public void GlobalSetup() + [GlobalSetup] + public void GlobalSetup() + { + Faker faker = new Faker().CustomInstantiator(f => new User { - Faker faker = new Faker().CustomInstantiator(f => new User - { - UserId = Guid.NewGuid(), - FirstName = f.Name.FirstName(), - LastName = f.Name.LastName(), - FullName = f.Name.FullName(), - Username = f.Internet.UserName(f.Name.FirstName(), f.Name.LastName()), - Email = f.Internet.Email(f.Name.FirstName(), f.Name.LastName()), - }); - _testUsers = faker.Generate(Count); - _serializedTestUsers = JsonSerializer.Serialize(_testUsers); - } + UserId = Guid.NewGuid(), + FirstName = f.Name.FirstName(), + LastName = f.Name.LastName(), + FullName = f.Name.FullName(), + Username = f.Internet.UserName(f.Name.FirstName(), f.Name.LastName()), + Email = f.Internet.Email(f.Name.FirstName(), f.Name.LastName()), + }); + _testUsers = faker.Generate(Count); + _serializedTestUsers = JsonSerializer.Serialize(_testUsers); + } - [Benchmark] - [BenchmarkCategory("Serialize", "Newtonsoft")] - public void NewtonsoftSerializeBigData() - { - _ = JsonConvert.SerializeObject(_testUsers); - } + [Benchmark] + [BenchmarkCategory("Serialize", "Newtonsoft")] + public void NewtonsoftSerializeBigData() + { + _ = JsonConvert.SerializeObject(_testUsers); + } - [Benchmark] - [BenchmarkCategory("Serialize", "Microsoft")] - public void MicrosoftSerializeBigData() - { - _ = JsonSerializer.Serialize(_testUsers); - } + [Benchmark] + [BenchmarkCategory("Serialize", "Microsoft")] + public void MicrosoftSerializeBigData() + { + _ = JsonSerializer.Serialize(_testUsers); + } - [Benchmark] - [BenchmarkCategory("Deserialize", "Newtonsoft")] - public void NewtonsoftDeserializeBigData() - { - _ = JsonConvert.DeserializeObject>(_serializedTestUsers); - } + [Benchmark] + [BenchmarkCategory("Deserialize", "Newtonsoft")] + public void NewtonsoftDeserializeBigData() + { + _ = JsonConvert.DeserializeObject>(_serializedTestUsers); + } - [Benchmark] - [BenchmarkCategory("Deserialize", "Microsoft")] - public void MicrosoftDeserializeBigData() - { - _ = JsonSerializer.Deserialize>(_serializedTestUsers); - } + [Benchmark] + [BenchmarkCategory("Deserialize", "Microsoft")] + public void MicrosoftDeserializeBigData() + { + _ = JsonSerializer.Deserialize>(_serializedTestUsers); } +} - //BenchmarkDotNet v0.13.11, Windows 11 (10.0.22631.3880/23H2/2023Update/SunValley3) - //Intel Core i7-10870H CPU 2.20GHz, 1 CPU, 16 logical and 8 physical cores - // .NET SDK 8.0.303 - // [Host] : .NET 6.0.32 (6.0.3224.31407), X64 RyuJIT AVX2[AttachedDebugger] - // .NET 8.0 : .NET 8.0.7 (8.0.724.31311), X64 RyuJIT AVX2 +//BenchmarkDotNet v0.13.11, Windows 11 (10.0.22631.3880/23H2/2023Update/SunValley3) +//Intel Core i7-10870H CPU 2.20GHz, 1 CPU, 16 logical and 8 physical cores +// .NET SDK 8.0.303 +// [Host] : .NET 6.0.32 (6.0.3224.31407), X64 RyuJIT AVX2[AttachedDebugger] +// .NET 8.0 : .NET 8.0.7 (8.0.724.31311), X64 RyuJIT AVX2 - // Job =.NET 8.0 Runtime=.NET 8.0 +// Job =.NET 8.0 Runtime=.NET 8.0 + +// | Method | Count | Mean | Error | StdDev | Median | Op/s | Gen0 | Gen1 | Gen2 | Allocated | +// |----------------------------- |------ |-----------:|---------:|----------:|-----------:|--------:|---------:|---------:|---------:|----------:| +// | MicrosoftDeserializeBigData | 1000 | 856.3 us | 53.98 us | 157.47 us | 797.1 us | 1,167.8 | 39.0625 | 13.6719 | - | 328.78 KB | +// | NewtonsoftDeserializeBigData | 1000 | 1,137.2 us | 18.74 us | 17.53 us | 1,132.8 us | 879.4 | 54.6875 | 17.5781 | - | 457.94 KB | +// |==============================================================================================================================================| +// | MicrosoftSerializeBigData | 1000 | 646.4 us | 12.72 us | 20.90 us | 645.7 us | 1,546.9 | 110.3516 | 110.3516 | 110.3516 | 350.02 KB | +// | NewtonsoftSerializeBigData | 1000 | 1,033.4 us | 19.37 us | 42.53 us | 1,022.8 us | 967.7 | 109.3750 | 109.3750 | 109.3750 | 837.82 KB | - // | Method | Count | Mean | Error | StdDev | Median | Op/s | Gen0 | Gen1 | Gen2 | Allocated | - // |----------------------------- |------ |-----------:|---------:|----------:|-----------:|--------:|---------:|---------:|---------:|----------:| - // | MicrosoftDeserializeBigData | 1000 | 856.3 us | 53.98 us | 157.47 us | 797.1 us | 1,167.8 | 39.0625 | 13.6719 | - | 328.78 KB | - // | NewtonsoftDeserializeBigData | 1000 | 1,137.2 us | 18.74 us | 17.53 us | 1,132.8 us | 879.4 | 54.6875 | 17.5781 | - | 457.94 KB | - // |==============================================================================================================================================| - // | MicrosoftSerializeBigData | 1000 | 646.4 us | 12.72 us | 20.90 us | 645.7 us | 1,546.9 | 110.3516 | 110.3516 | 110.3516 | 350.02 KB | - // | NewtonsoftSerializeBigData | 1000 | 1,033.4 us | 19.37 us | 42.53 us | 1,022.8 us | 967.7 | 109.3750 | 109.3750 | 109.3750 | 837.82 KB | -} public class User { diff --git a/test/Ocelot.IntegrationTests/AdministrationTests.cs b/test/Ocelot.IntegrationTests/AdministrationTests.cs index 921597b87..16c9d1b83 100644 --- a/test/Ocelot.IntegrationTests/AdministrationTests.cs +++ b/test/Ocelot.IntegrationTests/AdministrationTests.cs @@ -9,7 +9,6 @@ using Microsoft.Extensions.Hosting; using Microsoft.IdentityModel.Tokens; using Ocelot.Administration; -using Ocelot.Cache; using Ocelot.Configuration.ChangeTracking; using Ocelot.Configuration.File; using Ocelot.DependencyInjection; diff --git a/test/Ocelot.UnitTests/JsonSerializerOptionsFactoryTests.cs b/test/Ocelot.UnitTests/JsonSerializerOptionsFactoryTests.cs index 81fd97d95..0647bffac 100644 --- a/test/Ocelot.UnitTests/JsonSerializerOptionsFactoryTests.cs +++ b/test/Ocelot.UnitTests/JsonSerializerOptionsFactoryTests.cs @@ -1,71 +1,71 @@ using Ocelot.Infrastructure; using System.Text.Json; -namespace Ocelot.UnitTests +namespace Ocelot.UnitTests; + +public class JsonSerializerOptionsFactoryTests : UnitTest { - public class JsonSerializerOptionsFactoryTests : UnitTest + [Fact] + public void should_json_path() { - [Fact] - public void should_json_path() - { - //Arrange - var json = "{\"id\":1,\"writerId\":1,\"postId\":2,\"text\":\"text1\"}"; - var path = "$writerId"; - var document = JsonDocument.Parse(json); + //Arrange + var json = "{\"id\":1,\"writerId\":1,\"postId\":2,\"text\":\"text1\"}"; + var path = "$writerId"; + var document = JsonDocument.Parse(json); - //Act - var result = document.ExtractValuesFromJsonPath(path); + //Act + var result = document.ExtractValuesFromJsonPath(path); - //Assert - result.ShouldBeEquivalentTo(new List { "1" }); - } + //Assert + result.ShouldBeEquivalentTo(new List { "1" }); + } - [Fact] - public void should_json_path_array() - { - //Arrange - var json = - "[{\"id\":1,\"writerId\":1,\"postId\":2,\"text\":\"text1\"},{\"id\":2,\"writerId\":1,\"postId\":2,\"text\":\"text2\"}]"; - var path = "$[*].writerId"; - var document = JsonDocument.Parse(json); + [Fact] + public void should_json_path_array() + { + //Arrange + var json = + "[{\"id\":1,\"writerId\":1,\"postId\":2,\"text\":\"text1\"},{\"id\":2,\"writerId\":1,\"postId\":2,\"text\":\"text2\"}]"; + var path = "$[*].writerId"; + var document = JsonDocument.Parse(json); - //Act - var result = document.ExtractValuesFromJsonPath(path); + //Act + var result = document.ExtractValuesFromJsonPath(path); - //Assert - result.ShouldBeEquivalentTo(new List { "1", "1" }); - } + //Assert + result.ShouldBeEquivalentTo(new List { "1", "1" }); + } - [Fact] - public void should_json_path_nested() - { - //Arrange - var json = - "[{\"id\":1,\"writerId\":1,\"postId\":2,\"text\":\"text1\",\"comments\":[{\"commentId\":1,\"text\":\"Good post!\"},{\"commentId\":2,\"text\":\"Nice post!\"}]},{\"id\":2,\"writerId\":2,\"postId\":2,\"text\":\"text2\",\"comments\":[{\"commentId\":3,\"text\":\"Interesting.\"}]}]"; - var path = "$[*].comments[*].text"; - var document = JsonDocument.Parse(json); + [Fact] + public void should_json_path_nested() + { + //Arrange + var json = + "[{\"id\":1,\"writerId\":1,\"postId\":2,\"text\":\"text1\",\"comments\":[{\"commentId\":1,\"text\":\"Good post!\"},{\"commentId\":2,\"text\":\"Nice post!\"}]},{\"id\":2,\"writerId\":2,\"postId\":2,\"text\":\"text2\",\"comments\":[{\"commentId\":3,\"text\":\"Interesting.\"}]}]"; + var path = "$[*].comments[*].text"; + var document = JsonDocument.Parse(json); - //Act - var result = document.ExtractValuesFromJsonPath(path); + //Act + var result = document.ExtractValuesFromJsonPath(path); - //Assert - result.ShouldBeEquivalentTo(new List { "Good post!", "Nice post!", "Interesting." }); - } + //Assert + result.ShouldBeEquivalentTo(new List { "Good post!", "Nice post!", "Interesting." }); + } - [Fact] - public void should_json_path_nested_null() - { - //Arrange - var json = - "[{\"id\":1,\"writerId\":1,\"postId\":2,\"text\":\"text1\",\"comments\":[{\"commentId\":1,\"text\":null},{\"commentId\":2,\"text\":\"Nice post!\"}]},{\"id\":2,\"writerId\":2,\"postId\":2,\"text\":\"text2\",\"comments\":[{\"commentId\":3,\"text\":\"Interesting.\"}]}]"; - var path = "$[*].comments[*].text"; - var document = JsonDocument.Parse(json); + [Fact] + public void should_json_path_nested_null() + { + //Arrange + var json = + "[{\"id\":1,\"writerId\":1,\"postId\":2,\"text\":\"text1\",\"comments\":[{\"commentId\":1,\"text\":null},{\"commentId\":2,\"text\":\"Nice post!\"}]},{\"id\":2,\"writerId\":2,\"postId\":2,\"text\":\"text2\",\"comments\":[{\"commentId\":3,\"text\":\"Interesting.\"}]}]"; + var path = "$[*].comments[*].text"; + var document = JsonDocument.Parse(json); - //Act - var result = document.ExtractValuesFromJsonPath(path); + //Act + var result = document.ExtractValuesFromJsonPath(path); - //Assert - result.ShouldBeEquivalentTo(new List { "Nice post!", "Interesting." }); - } + //Assert + result.ShouldBeEquivalentTo(new List { "Nice post!", "Interesting." }); } } + From 6b67250c2e08ebc3e92c7107d1fb47ed314dc89e Mon Sep 17 00:00:00 2001 From: Raman Maksimchuk Date: Fri, 20 Dec 2024 14:17:44 +0300 Subject: [PATCH 24/26] Fix build errors, warnings, messages after rebasing --- test/Ocelot.Benchmarks/JsonSerializerBenchmark.cs | 2 -- test/Ocelot.Benchmarks/Ocelot.Benchmarks.csproj | 1 - .../DependencyInjection/OcelotBuilderTests.cs | 6 +++--- test/Ocelot.UnitTests/JsonSerializerOptionsFactoryTests.cs | 1 - 4 files changed, 3 insertions(+), 7 deletions(-) diff --git a/test/Ocelot.Benchmarks/JsonSerializerBenchmark.cs b/test/Ocelot.Benchmarks/JsonSerializerBenchmark.cs index 046bb47a2..37c6f3036 100644 --- a/test/Ocelot.Benchmarks/JsonSerializerBenchmark.cs +++ b/test/Ocelot.Benchmarks/JsonSerializerBenchmark.cs @@ -76,8 +76,6 @@ public void MicrosoftDeserializeBigData() // |==============================================================================================================================================| // | MicrosoftSerializeBigData | 1000 | 646.4 us | 12.72 us | 20.90 us | 645.7 us | 1,546.9 | 110.3516 | 110.3516 | 110.3516 | 350.02 KB | // | NewtonsoftSerializeBigData | 1000 | 1,033.4 us | 19.37 us | 42.53 us | 1,022.8 us | 967.7 | 109.3750 | 109.3750 | 109.3750 | 837.82 KB | - - public class User { public Guid UserId { get; set; } diff --git a/test/Ocelot.Benchmarks/Ocelot.Benchmarks.csproj b/test/Ocelot.Benchmarks/Ocelot.Benchmarks.csproj index e18d87e72..21d46e681 100644 --- a/test/Ocelot.Benchmarks/Ocelot.Benchmarks.csproj +++ b/test/Ocelot.Benchmarks/Ocelot.Benchmarks.csproj @@ -25,7 +25,6 @@ - diff --git a/test/Ocelot.UnitTests/DependencyInjection/OcelotBuilderTests.cs b/test/Ocelot.UnitTests/DependencyInjection/OcelotBuilderTests.cs index 010751832..7fc9fa8dc 100644 --- a/test/Ocelot.UnitTests/DependencyInjection/OcelotBuilderTests.cs +++ b/test/Ocelot.UnitTests/DependencyInjection/OcelotBuilderTests.cs @@ -324,9 +324,9 @@ private void CstorShouldUseDefaultBuilderToInitMvcCoreBuilder() .GetType().Name.ShouldBe("AuthorizationApplicationModelProvider"); // use system text json - _serviceProvider.GetServices>() - .FirstOrDefault(s => s.GetType().Name == "SystemTextJsonResultExecutor") - .ShouldNotBeNull(); + _serviceProvider.GetServices>() + .FirstOrDefault(s => s.GetType().Name == "SystemTextJsonResultExecutor") + .ShouldNotBeNull(); } [Fact] diff --git a/test/Ocelot.UnitTests/JsonSerializerOptionsFactoryTests.cs b/test/Ocelot.UnitTests/JsonSerializerOptionsFactoryTests.cs index 0647bffac..9e00d5fcc 100644 --- a/test/Ocelot.UnitTests/JsonSerializerOptionsFactoryTests.cs +++ b/test/Ocelot.UnitTests/JsonSerializerOptionsFactoryTests.cs @@ -68,4 +68,3 @@ public void should_json_path_nested_null() result.ShouldBeEquivalentTo(new List { "Nice post!", "Interesting." }); } } - From f59ca5ea95f2ffa5df8d2a0ad527b704fea8aedb Mon Sep 17 00:00:00 2001 From: Mohsen Rajabi Date: Sat, 21 Dec 2024 08:21:39 +0330 Subject: [PATCH 25/26] fix: rm newstonsoft --- src/Ocelot/Ocelot.csproj | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/Ocelot/Ocelot.csproj b/src/Ocelot/Ocelot.csproj index bc9bd93fc..a0fc7411a 100644 --- a/src/Ocelot/Ocelot.csproj +++ b/src/Ocelot/Ocelot.csproj @@ -31,7 +31,6 @@ - NU1701 @@ -43,12 +42,12 @@ - + - + From 2a213d2a2b454324a56a765aaaadecf9cf28a5ac Mon Sep 17 00:00:00 2001 From: Mohsen Rajabi Date: Sat, 21 Dec 2024 08:28:50 +0330 Subject: [PATCH 26/26] fix: rename JsonSerializerOptionsFactory to OcelotSerializerOptions --- .../ConsulFileConfigurationRepository.cs | 4 ++-- .../Repository/DiskFileConfigurationRepository.cs | 4 ++-- .../Repository/FileConfigurationPoller.cs | 2 +- .../ConfigurationBuilderExtensions.cs | 6 +++--- ...ptionsFactory.cs => OcelotSerializerOptions.cs} | 2 +- src/Ocelot/Metadata/DownstreamRouteExtensions.cs | 2 +- .../DistributedCacheRateLimitStorage.cs | 4 ++-- .../Ocelot.AcceptanceTests/Caching/CachingTests.cs | 4 ++-- .../Configuration/ConfigurationInConsulTests.cs | 6 +++--- .../ConsulConfigurationInConsulTests.cs | 10 +++++----- .../ConsulServiceDiscoveryTests.cs | 4 ++-- .../ServiceDiscovery/ConsulWebSocketTests.cs | 2 +- .../EurekaServiceDiscoveryTests.cs | 2 +- .../KubernetesServiceDiscoveryTests.cs | 2 +- test/Ocelot.AcceptanceTests/Steps.cs | 6 +++--- .../TwoDownstreamServicesTests.cs | 2 +- test/Ocelot.Benchmarks/AllTheThingsBenchmarks.cs | 2 +- test/Ocelot.Benchmarks/MsLoggerBenchmarks.cs | 2 +- test/Ocelot.Benchmarks/PayloadBenchmarks.cs | 2 +- test/Ocelot.Benchmarks/ResponseBenchmarks.cs | 2 +- test/Ocelot.Benchmarks/SerilogBenchmarks.cs | 2 +- .../Ocelot.IntegrationTests/AdministrationTests.cs | 14 +++++++------- test/Ocelot.IntegrationTests/CacheManagerTests.cs | 4 ++-- test/Ocelot.IntegrationTests/HeaderTests.cs | 2 +- .../ThreadSafeHeadersTests.cs | 2 +- test/Ocelot.ManualTest/CustomOcelotMiddleware.cs | 2 +- .../DiskFileConfigurationRepositoryTests.cs | 6 +++--- .../ConsulFileConfigurationRepositoryTests.cs | 8 ++++---- test/Ocelot.UnitTests/Consul/ConsulTests.cs | 2 +- .../ConfigurationBuilderExtensionsTests.cs | 2 +- test/Ocelot.UnitTests/Kubernetes/KubeTests.cs | 2 +- ...oryTests.cs => OcelotSerializerOptionsTests.cs} | 2 +- 32 files changed, 59 insertions(+), 59 deletions(-) rename src/Ocelot/Infrastructure/{JsonSerializerOptionsFactory.cs => OcelotSerializerOptions.cs} (98%) rename test/Ocelot.UnitTests/{JsonSerializerOptionsFactoryTests.cs => OcelotSerializerOptionsTests.cs} (97%) diff --git a/src/Ocelot.Provider.Consul/ConsulFileConfigurationRepository.cs b/src/Ocelot.Provider.Consul/ConsulFileConfigurationRepository.cs index e79245a1b..b57c83bc3 100644 --- a/src/Ocelot.Provider.Consul/ConsulFileConfigurationRepository.cs +++ b/src/Ocelot.Provider.Consul/ConsulFileConfigurationRepository.cs @@ -54,14 +54,14 @@ public async Task> Get() var bytes = queryResult.Response.Value; var json = Encoding.UTF8.GetString(bytes); - var consulConfig = JsonSerializer.Deserialize(json, JsonSerializerOptionsFactory.Web); + var consulConfig = JsonSerializer.Deserialize(json, OcelotSerializerOptions.Web); return new OkResponse(consulConfig); } public async Task Set(FileConfiguration ocelotConfiguration) { - var json = JsonSerializer.Serialize(ocelotConfiguration, JsonSerializerOptionsFactory.WebWriteIndented); + var json = JsonSerializer.Serialize(ocelotConfiguration, OcelotSerializerOptions.WebWriteIndented); var bytes = Encoding.UTF8.GetBytes(json); var kvPair = new KVPair(_configurationKey) { diff --git a/src/Ocelot/Configuration/Repository/DiskFileConfigurationRepository.cs b/src/Ocelot/Configuration/Repository/DiskFileConfigurationRepository.cs index ad4abf8c2..41675e417 100644 --- a/src/Ocelot/Configuration/Repository/DiskFileConfigurationRepository.cs +++ b/src/Ocelot/Configuration/Repository/DiskFileConfigurationRepository.cs @@ -50,14 +50,14 @@ public Task> Get() jsonConfiguration = FileSys.ReadAllText(_environmentFile.FullName); } - var fileConfiguration = JsonSerializer.Deserialize(jsonConfiguration, JsonSerializerOptionsFactory.Web); + var fileConfiguration = JsonSerializer.Deserialize(jsonConfiguration, OcelotSerializerOptions.Web); return Task.FromResult>(new OkResponse(fileConfiguration)); } public Task Set(FileConfiguration fileConfiguration) { - var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsFactory.WebWriteIndented); + var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, OcelotSerializerOptions.WebWriteIndented); lock (_lock) { diff --git a/src/Ocelot/Configuration/Repository/FileConfigurationPoller.cs b/src/Ocelot/Configuration/Repository/FileConfigurationPoller.cs index 080f18fff..9e40de50d 100644 --- a/src/Ocelot/Configuration/Repository/FileConfigurationPoller.cs +++ b/src/Ocelot/Configuration/Repository/FileConfigurationPoller.cs @@ -96,7 +96,7 @@ private async Task Poll() /// hash of the config. private static string ToJson(FileConfiguration config) { - var currentHash = JsonSerializer.Serialize(config, JsonSerializerOptionsFactory.Web); + var currentHash = JsonSerializer.Serialize(config, OcelotSerializerOptions.Web); return currentHash; } diff --git a/src/Ocelot/DependencyInjection/ConfigurationBuilderExtensions.cs b/src/Ocelot/DependencyInjection/ConfigurationBuilderExtensions.cs index 76955dee3..2118200bf 100644 --- a/src/Ocelot/DependencyInjection/ConfigurationBuilderExtensions.cs +++ b/src/Ocelot/DependencyInjection/ConfigurationBuilderExtensions.cs @@ -134,7 +134,7 @@ private static string GetMergedOcelotJson(string folder, IWebHostEnvironment env } var lines = File.ReadAllText(file.FullName); - var config = JsonSerializer.Deserialize(lines, JsonSerializerOptionsFactory.Web); + var config = JsonSerializer.Deserialize(lines, OcelotSerializerOptions.Web); if (file.Name.Equals(globalFileInfo.Name, StringComparison.OrdinalIgnoreCase) && file.FullName.Equals(globalFileInfo.FullName, StringComparison.OrdinalIgnoreCase)) { @@ -145,7 +145,7 @@ private static string GetMergedOcelotJson(string folder, IWebHostEnvironment env fileConfiguration.Routes.AddRange(config.Routes); } - return JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsFactory.WebWriteIndented); + return JsonSerializer.Serialize(fileConfiguration, OcelotSerializerOptions.WebWriteIndented); } /// @@ -162,7 +162,7 @@ private static string GetMergedOcelotJson(string folder, IWebHostEnvironment env public static IConfigurationBuilder AddOcelot(this IConfigurationBuilder builder, FileConfiguration fileConfiguration, string primaryConfigFile = null, bool? optional = null, bool? reloadOnChange = null) // optional injections { - var json = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsFactory.WebWriteIndented); + var json = JsonSerializer.Serialize(fileConfiguration, OcelotSerializerOptions.WebWriteIndented); return AddOcelotJsonFile(builder, json, primaryConfigFile, optional, reloadOnChange); } diff --git a/src/Ocelot/Infrastructure/JsonSerializerOptionsFactory.cs b/src/Ocelot/Infrastructure/OcelotSerializerOptions.cs similarity index 98% rename from src/Ocelot/Infrastructure/JsonSerializerOptionsFactory.cs rename to src/Ocelot/Infrastructure/OcelotSerializerOptions.cs index 4cd4b695a..6f40987ab 100644 --- a/src/Ocelot/Infrastructure/JsonSerializerOptionsFactory.cs +++ b/src/Ocelot/Infrastructure/OcelotSerializerOptions.cs @@ -5,7 +5,7 @@ namespace Ocelot.Infrastructure; -public static class JsonSerializerOptionsFactory +public static class OcelotSerializerOptions { public static readonly JsonSerializerOptions Web = new() { diff --git a/src/Ocelot/Metadata/DownstreamRouteExtensions.cs b/src/Ocelot/Metadata/DownstreamRouteExtensions.cs index 9ee87b83a..2d62f7f8c 100644 --- a/src/Ocelot/Metadata/DownstreamRouteExtensions.cs +++ b/src/Ocelot/Metadata/DownstreamRouteExtensions.cs @@ -74,7 +74,7 @@ public static T GetMetadata(this DownstreamRoute downstreamRoute, string key, } return (T)ConvertTo(typeof(T), metadataValue, downstreamRoute.MetadataOptions, - jsonSerializerOptions ?? JsonSerializerOptionsFactory.Web); + jsonSerializerOptions ?? OcelotSerializerOptions.Web); } /// diff --git a/src/Ocelot/RateLimiting/DistributedCacheRateLimitStorage.cs b/src/Ocelot/RateLimiting/DistributedCacheRateLimitStorage.cs index 2ab786eb2..f1934a903 100644 --- a/src/Ocelot/RateLimiting/DistributedCacheRateLimitStorage.cs +++ b/src/Ocelot/RateLimiting/DistributedCacheRateLimitStorage.cs @@ -17,7 +17,7 @@ public class DistributedCacheRateLimitStorage : IRateLimitStorage public DistributedCacheRateLimitStorage(IDistributedCache memoryCache) => _memoryCache = memoryCache; public void Set(string id, RateLimitCounter counter, TimeSpan expirationTime) - => _memoryCache.SetString(id, JsonSerializer.Serialize(counter, JsonSerializerOptionsFactory.Web), new DistributedCacheEntryOptions().SetAbsoluteExpiration(expirationTime)); + => _memoryCache.SetString(id, JsonSerializer.Serialize(counter, OcelotSerializerOptions.Web), new DistributedCacheEntryOptions().SetAbsoluteExpiration(expirationTime)); public bool Exists(string id) => !string.IsNullOrEmpty(_memoryCache.GetString(id)); @@ -25,7 +25,7 @@ public void Set(string id, RateLimitCounter counter, TimeSpan expirationTime) { var stored = _memoryCache.GetString(id); return !string.IsNullOrEmpty(stored) - ? JsonSerializer.Deserialize(stored, JsonSerializerOptionsFactory.Web) + ? JsonSerializer.Deserialize(stored, OcelotSerializerOptions.Web) : null; } diff --git a/test/Ocelot.AcceptanceTests/Caching/CachingTests.cs b/test/Ocelot.AcceptanceTests/Caching/CachingTests.cs index 86fd1dcb5..10b50e3cc 100644 --- a/test/Ocelot.AcceptanceTests/Caching/CachingTests.cs +++ b/test/Ocelot.AcceptanceTests/Caching/CachingTests.cs @@ -299,7 +299,7 @@ private void ThenTheCounterValueShouldBe(int expected) LastName = "Test", }; - var testBody1String = JsonSerializer.Serialize(testBody1, JsonSerializerOptionsFactory.Web); + var testBody1String = JsonSerializer.Serialize(testBody1, OcelotSerializerOptions.Web); var testBody2 = new TestBody { @@ -309,7 +309,7 @@ private void ThenTheCounterValueShouldBe(int expected) LastName = "Test", }; - var testBody2String = JsonSerializer.Serialize(testBody2, JsonSerializerOptionsFactory.Web); + var testBody2String = JsonSerializer.Serialize(testBody2, OcelotSerializerOptions.Web); return (testBody1String, testBody2String); } diff --git a/test/Ocelot.AcceptanceTests/Configuration/ConfigurationInConsulTests.cs b/test/Ocelot.AcceptanceTests/Configuration/ConfigurationInConsulTests.cs index f966fa1ed..4daa932f9 100644 --- a/test/Ocelot.AcceptanceTests/Configuration/ConfigurationInConsulTests.cs +++ b/test/Ocelot.AcceptanceTests/Configuration/ConfigurationInConsulTests.cs @@ -131,7 +131,7 @@ private Task GivenThereIsAFakeConsulServiceDiscoveryProvider(string url, string { if (context.Request.Method.ToLower() == "get" && context.Request.Path.Value == "/v1/kv/InternalConfiguration") { - var json = JsonSerializer.Serialize(_config, JsonSerializerOptionsFactory.Web); + var json = JsonSerializer.Serialize(_config, OcelotSerializerOptions.Web); var bytes = Encoding.UTF8.GetBytes(json); @@ -151,9 +151,9 @@ private Task GivenThereIsAFakeConsulServiceDiscoveryProvider(string url, string // var json = reader.ReadToEnd(); var json = await reader.ReadToEndAsync(); - _config = JsonSerializer.Deserialize(json, JsonSerializerOptionsFactory.Web); + _config = JsonSerializer.Deserialize(json, OcelotSerializerOptions.Web); - var response = JsonSerializer.Serialize(true, JsonSerializerOptionsFactory.Web); + var response = JsonSerializer.Serialize(true, OcelotSerializerOptions.Web); await context.Response.WriteAsync(response); } diff --git a/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulConfigurationInConsulTests.cs b/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulConfigurationInConsulTests.cs index 41c82f5bb..7017c4ecb 100644 --- a/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulConfigurationInConsulTests.cs +++ b/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulConfigurationInConsulTests.cs @@ -387,14 +387,14 @@ private Task GivenThereIsAFakeConsulServiceDiscoveryProvider(string url, string { if (context.Request.Method.ToLower() == "get" && context.Request.Path.Value == "/v1/kv/InternalConfiguration") { - var json = JsonSerializer.Serialize(_config, JsonSerializerOptionsFactory.Web); + var json = JsonSerializer.Serialize(_config, OcelotSerializerOptions.Web); var bytes = Encoding.UTF8.GetBytes(json); var base64 = Convert.ToBase64String(bytes); var kvp = new FakeConsulGetResponse(base64); - json = JsonSerializer.Serialize(new[] { kvp }, JsonSerializerOptionsFactory.Web); + json = JsonSerializer.Serialize(new[] { kvp }, OcelotSerializerOptions.Web); context.Response.Headers.Append("Content-Type", "application/json"); await context.Response.WriteAsync(json); } @@ -408,9 +408,9 @@ private Task GivenThereIsAFakeConsulServiceDiscoveryProvider(string url, string // var json = reader.ReadToEnd(); var json = await reader.ReadToEndAsync(); - _config = JsonSerializer.Deserialize(json, JsonSerializerOptionsFactory.Web); + _config = JsonSerializer.Deserialize(json, OcelotSerializerOptions.Web); - var response = JsonSerializer.Serialize(true, JsonSerializerOptionsFactory.Web); + var response = JsonSerializer.Serialize(true, OcelotSerializerOptions.Web); await context.Response.WriteAsync(response); } @@ -422,7 +422,7 @@ private Task GivenThereIsAFakeConsulServiceDiscoveryProvider(string url, string } else if (context.Request.Path.Value == $"/v1/health/service/{serviceName}") { - var json = JsonSerializer.Serialize(_consulServices, JsonSerializerOptionsFactory.Web); + var json = JsonSerializer.Serialize(_consulServices, OcelotSerializerOptions.Web); context.Response.Headers.Append("Content-Type", "application/json"); await context.Response.WriteAsync(json); } diff --git a/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulServiceDiscoveryTests.cs b/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulServiceDiscoveryTests.cs index ed49bdb36..561a02153 100644 --- a/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulServiceDiscoveryTests.cs +++ b/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulServiceDiscoveryTests.cs @@ -619,7 +619,7 @@ private void GivenThereIsAFakeConsulServiceDiscoveryProvider(string url) // Use the parsed service name to filter the registered Consul services var serviceName = pathMatch.Groups["serviceName"].Value; var services = _consulServices.Where(x => x.Service.Service == serviceName).ToList(); - var json = JsonSerializer.Serialize(services, JsonSerializerOptionsFactory.Web); + var json = JsonSerializer.Serialize(services, OcelotSerializerOptions.Web); json = json.Replace("\"Name\":", "\"Node\":"); //} @@ -632,7 +632,7 @@ private void GivenThereIsAFakeConsulServiceDiscoveryProvider(string url) { //_counterNodes++; int count = Interlocked.Increment(ref _counterNodes); - var json = JsonSerializer.Serialize(_consulNodes, JsonSerializerOptionsFactory.Web); + var json = JsonSerializer.Serialize(_consulNodes, OcelotSerializerOptions.Web); context.Response.Headers.Append("Content-Type", "application/json"); await context.Response.WriteAsync(json); } diff --git a/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulWebSocketTests.cs b/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulWebSocketTests.cs index 1f39471c4..7bdd94d1d 100644 --- a/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulWebSocketTests.cs +++ b/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulWebSocketTests.cs @@ -175,7 +175,7 @@ private void GivenThereIsAFakeConsulServiceDiscoveryProvider(int port, string se { if (context.Request.Path.Value == $"/v1/health/service/{serviceName}") { - var json = JsonSerializer.Serialize(_serviceEntries, JsonSerializerOptionsFactory.Web); + var json = JsonSerializer.Serialize(_serviceEntries, OcelotSerializerOptions.Web); context.Response.Headers.Append("Content-Type", "application/json"); await context.Response.WriteAsync(json); } diff --git a/test/Ocelot.AcceptanceTests/ServiceDiscovery/EurekaServiceDiscoveryTests.cs b/test/Ocelot.AcceptanceTests/ServiceDiscovery/EurekaServiceDiscoveryTests.cs index c43669121..dd499cc81 100644 --- a/test/Ocelot.AcceptanceTests/ServiceDiscovery/EurekaServiceDiscoveryTests.cs +++ b/test/Ocelot.AcceptanceTests/ServiceDiscovery/EurekaServiceDiscoveryTests.cs @@ -144,7 +144,7 @@ private void GivenThereIsAFakeEurekaServiceDiscoveryProvider(string url, string }, }; - var json = JsonSerializer.Serialize(applications, JsonSerializerOptionsFactory.Web); + var json = JsonSerializer.Serialize(applications, OcelotSerializerOptions.Web); context.Response.Headers.Append("Content-Type", "application/json"); await context.Response.WriteAsync(json); } diff --git a/test/Ocelot.AcceptanceTests/ServiceDiscovery/KubernetesServiceDiscoveryTests.cs b/test/Ocelot.AcceptanceTests/ServiceDiscovery/KubernetesServiceDiscoveryTests.cs index 9857760e0..901de9f57 100644 --- a/test/Ocelot.AcceptanceTests/ServiceDiscovery/KubernetesServiceDiscoveryTests.cs +++ b/test/Ocelot.AcceptanceTests/ServiceDiscovery/KubernetesServiceDiscoveryTests.cs @@ -295,7 +295,7 @@ private void GivenThereIsAFakeKubernetesProvider(EndpointsV1 endpoints, bool isS } endpoints.Metadata.Generation = _k8sServiceGeneration; - json = JsonSerializer.Serialize(endpoints, JsonSerializerOptionsFactory.Web); + json = JsonSerializer.Serialize(endpoints, OcelotSerializerOptions.Web); } if (context.Request.Headers.TryGetValue("Authorization", out var values)) diff --git a/test/Ocelot.AcceptanceTests/Steps.cs b/test/Ocelot.AcceptanceTests/Steps.cs index c73fab9c0..710a0c0e3 100644 --- a/test/Ocelot.AcceptanceTests/Steps.cs +++ b/test/Ocelot.AcceptanceTests/Steps.cs @@ -166,7 +166,7 @@ protected string SerializeJson(FileConfiguration from, ref string toFile) { toFile ??= _ocelotConfigFileName; Files.Add(toFile); // register for disposing - return JsonSerializer.Serialize(from, JsonSerializerOptionsFactory.WebWriteIndented); + return JsonSerializer.Serialize(from, OcelotSerializerOptions.WebWriteIndented); } protected virtual void DeleteFiles() @@ -619,7 +619,7 @@ internal async Task GivenIHaveATokenWithForm(string url, IEnumerabl var response = await httpClient.PostAsync(tokenUrl, content); var responseContent = await response.Content.ReadAsStringAsync(); response.EnsureSuccessStatusCode(); - _token = JsonSerializer.Deserialize(responseContent, JsonSerializerOptionsFactory.Web); + _token = JsonSerializer.Deserialize(responseContent, OcelotSerializerOptions.Web); return _token; } @@ -759,7 +759,7 @@ public void GivenThePostHasContentType(string postContent) public void GivenThePostHasGzipContent(object input) { - var json = JsonSerializer.Serialize(input, JsonSerializerOptionsFactory.Web); + var json = JsonSerializer.Serialize(input, OcelotSerializerOptions.Web); var jsonBytes = Encoding.UTF8.GetBytes(json); var ms = new MemoryStream(); using (var gzip = new GZipStream(ms, CompressionMode.Compress, true)) diff --git a/test/Ocelot.AcceptanceTests/TwoDownstreamServicesTests.cs b/test/Ocelot.AcceptanceTests/TwoDownstreamServicesTests.cs index dcb93c1f2..fb55d92fd 100644 --- a/test/Ocelot.AcceptanceTests/TwoDownstreamServicesTests.cs +++ b/test/Ocelot.AcceptanceTests/TwoDownstreamServicesTests.cs @@ -97,7 +97,7 @@ private void GivenThereIsAFakeConsulServiceDiscoveryProvider(string url) { if (context.Request.Path.Value == "/v1/health/service/product") { - var json = JsonSerializer.Serialize(_serviceEntries, JsonSerializerOptionsFactory.Web); + var json = JsonSerializer.Serialize(_serviceEntries, OcelotSerializerOptions.Web); context.Response.Headers.Append("Content-Type", "application/json"); await context.Response.WriteAsync(json); } diff --git a/test/Ocelot.Benchmarks/AllTheThingsBenchmarks.cs b/test/Ocelot.Benchmarks/AllTheThingsBenchmarks.cs index 4694c2c82..b8506b3b8 100644 --- a/test/Ocelot.Benchmarks/AllTheThingsBenchmarks.cs +++ b/test/Ocelot.Benchmarks/AllTheThingsBenchmarks.cs @@ -113,7 +113,7 @@ public static void GivenThereIsAConfiguration(FileConfiguration fileConfiguratio { var configurationPath = Path.Combine(AppContext.BaseDirectory, "ocelot.json"); - var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsFactory.Web); + var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, OcelotSerializerOptions.Web); if (File.Exists(configurationPath)) { diff --git a/test/Ocelot.Benchmarks/MsLoggerBenchmarks.cs b/test/Ocelot.Benchmarks/MsLoggerBenchmarks.cs index 11f325210..dcda051cd 100644 --- a/test/Ocelot.Benchmarks/MsLoggerBenchmarks.cs +++ b/test/Ocelot.Benchmarks/MsLoggerBenchmarks.cs @@ -163,7 +163,7 @@ public static void GivenThereIsAConfiguration(FileConfiguration fileConfiguratio { var configurationPath = Path.Combine(AppContext.BaseDirectory, "ocelot.json"); - var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsFactory.Web); + var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, OcelotSerializerOptions.Web); if (File.Exists(configurationPath)) { diff --git a/test/Ocelot.Benchmarks/PayloadBenchmarks.cs b/test/Ocelot.Benchmarks/PayloadBenchmarks.cs index bf58087e6..8db6ac2e2 100644 --- a/test/Ocelot.Benchmarks/PayloadBenchmarks.cs +++ b/test/Ocelot.Benchmarks/PayloadBenchmarks.cs @@ -221,7 +221,7 @@ private void GivenOcelotIsRunning(string url) public static void GivenThereIsAConfiguration(FileConfiguration fileConfiguration) { var configurationPath = Path.Combine(AppContext.BaseDirectory, ConfigurationBuilderExtensions.PrimaryConfigFile); - var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsFactory.Web); + var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, OcelotSerializerOptions.Web); if (File.Exists(configurationPath)) { diff --git a/test/Ocelot.Benchmarks/ResponseBenchmarks.cs b/test/Ocelot.Benchmarks/ResponseBenchmarks.cs index 75c00d143..50f67f96e 100644 --- a/test/Ocelot.Benchmarks/ResponseBenchmarks.cs +++ b/test/Ocelot.Benchmarks/ResponseBenchmarks.cs @@ -222,7 +222,7 @@ private void GivenOcelotIsRunning(string url) public static void GivenThereIsAConfiguration(FileConfiguration fileConfiguration) { var configurationPath = Path.Combine(AppContext.BaseDirectory, ConfigurationBuilderExtensions.PrimaryConfigFile); - var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsFactory.Web); + var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, OcelotSerializerOptions.Web); if (File.Exists(configurationPath)) { diff --git a/test/Ocelot.Benchmarks/SerilogBenchmarks.cs b/test/Ocelot.Benchmarks/SerilogBenchmarks.cs index d6fff6971..6644faae9 100644 --- a/test/Ocelot.Benchmarks/SerilogBenchmarks.cs +++ b/test/Ocelot.Benchmarks/SerilogBenchmarks.cs @@ -194,7 +194,7 @@ public static void GivenThereIsAConfiguration(FileConfiguration fileConfiguratio { var configurationPath = Path.Combine(AppContext.BaseDirectory, "ocelot.json"); - var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsFactory.Web); + var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, OcelotSerializerOptions.Web); if (File.Exists(configurationPath)) { diff --git a/test/Ocelot.IntegrationTests/AdministrationTests.cs b/test/Ocelot.IntegrationTests/AdministrationTests.cs index 16c9d1b83..5c714272e 100644 --- a/test/Ocelot.IntegrationTests/AdministrationTests.cs +++ b/test/Ocelot.IntegrationTests/AdministrationTests.cs @@ -342,12 +342,12 @@ private static void ThenTheConfigurationIsSavedCorrectly(FileConfiguration expec { var ocelotJsonPath = $"{AppContext.BaseDirectory}ocelot.json"; var resultText = File.ReadAllText(ocelotJsonPath); - var expectedText = JsonSerializer.Serialize(expected, JsonSerializerOptionsFactory.WebWriteIndented); + var expectedText = JsonSerializer.Serialize(expected, OcelotSerializerOptions.WebWriteIndented); resultText.ShouldBe(expectedText); var environmentSpecificPath = $"{AppContext.BaseDirectory}/ocelot.Production.json"; resultText = File.ReadAllText(environmentSpecificPath); - expectedText = JsonSerializer.Serialize(expected, JsonSerializerOptionsFactory.WebWriteIndented); + expectedText = JsonSerializer.Serialize(expected, OcelotSerializerOptions.WebWriteIndented); resultText.ShouldBe(expectedText); } @@ -523,7 +523,7 @@ private async Task GivenIHaveAToken(string url) var response = await httpClient.PostAsync($"{url}/connect/token", content); var responseContent = await response.Content.ReadAsStringAsync(); response.EnsureSuccessStatusCode(); - _token = JsonSerializer.Deserialize(responseContent, JsonSerializerOptionsFactory.Web); + _token = JsonSerializer.Deserialize(responseContent, OcelotSerializerOptions.Web); } private async Task GivenThereIsAnIdentityServerOn(string url, string apiName) @@ -640,7 +640,7 @@ private async Task WhenIGetUrlOnTheSecondOcelot(string url) private async Task WhenIPostOnTheApiGateway(string url, FileConfiguration updatedConfiguration) { - var json = JsonSerializer.Serialize(updatedConfiguration, JsonSerializerOptionsFactory.Web); + var json = JsonSerializer.Serialize(updatedConfiguration, OcelotSerializerOptions.Web); var content = new StringContent(json); content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); _response = await _httpClient.PostAsync(url, content); @@ -654,7 +654,7 @@ private async Task ThenTheResponseBodyShouldBe(string expected) private async Task ThenTheResponseShouldBe(FileConfiguration expecteds) { - var response = JsonSerializer.Deserialize(await _response.Content.ReadAsStringAsync(), JsonSerializerOptionsFactory.Web); + var response = JsonSerializer.Deserialize(await _response.Content.ReadAsStringAsync(), OcelotSerializerOptions.Web); response.GlobalConfiguration.RequestIdKey.ShouldBe(expecteds.GlobalConfiguration.RequestIdKey); response.GlobalConfiguration.ServiceDiscoveryProvider.Scheme.ShouldBe(expecteds.GlobalConfiguration.ServiceDiscoveryProvider.Scheme); @@ -698,7 +698,7 @@ private async Task GivenIHaveAnOcelotToken(string adminPath) var response = await _httpClient.PostAsync(tokenUrl, content); var responseContent = await response.Content.ReadAsStringAsync(); response.EnsureSuccessStatusCode(); - _token = JsonSerializer.Deserialize(responseContent, JsonSerializerOptionsFactory.Web); + _token = JsonSerializer.Deserialize(responseContent, OcelotSerializerOptions.Web); var configPath = $"{adminPath}/.well-known/openid-configuration"; response = await _httpClient.GetAsync(configPath); response.EnsureSuccessStatusCode(); @@ -825,7 +825,7 @@ private static async Task GivenThereIsAConfiguration(FileConfiguration fileConfi { var configurationPath = $"{Directory.GetCurrentDirectory()}/ocelot.json"; - var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsFactory.Web); + var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, OcelotSerializerOptions.Web); if (File.Exists(configurationPath)) { diff --git a/test/Ocelot.IntegrationTests/CacheManagerTests.cs b/test/Ocelot.IntegrationTests/CacheManagerTests.cs index 484a4220c..9f388806d 100644 --- a/test/Ocelot.IntegrationTests/CacheManagerTests.cs +++ b/test/Ocelot.IntegrationTests/CacheManagerTests.cs @@ -112,7 +112,7 @@ private async Task GivenIHaveAnOcelotToken(string adminPath) var response = await _httpClient.PostAsync(tokenUrl, content); var responseContent = await response.Content.ReadAsStringAsync(); response.EnsureSuccessStatusCode(); - _token = JsonSerializer.Deserialize(responseContent, JsonSerializerOptionsFactory.Web); + _token = JsonSerializer.Deserialize(responseContent, OcelotSerializerOptions.Web); var configPath = $"{adminPath}/.well-known/openid-configuration"; response = await _httpClient.GetAsync(configPath); response.EnsureSuccessStatusCode(); @@ -162,7 +162,7 @@ private static void GivenThereIsAConfiguration(FileConfiguration fileConfigurati // TODO: Turn method as async var configurationPath = $"{Directory.GetCurrentDirectory()}/ocelot.json"; - var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsFactory.Web); + var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, OcelotSerializerOptions.Web); if (File.Exists(configurationPath)) { diff --git a/test/Ocelot.IntegrationTests/HeaderTests.cs b/test/Ocelot.IntegrationTests/HeaderTests.cs index 963f4fc55..bb5d65e84 100644 --- a/test/Ocelot.IntegrationTests/HeaderTests.cs +++ b/test/Ocelot.IntegrationTests/HeaderTests.cs @@ -123,7 +123,7 @@ private static void GivenThereIsAConfiguration(FileConfiguration fileConfigurati { var configurationPath = $"{Directory.GetCurrentDirectory()}/ocelot.json"; - var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsFactory.Web); + var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, OcelotSerializerOptions.Web); if (File.Exists(configurationPath)) { diff --git a/test/Ocelot.IntegrationTests/ThreadSafeHeadersTests.cs b/test/Ocelot.IntegrationTests/ThreadSafeHeadersTests.cs index bb638d821..bd6974012 100644 --- a/test/Ocelot.IntegrationTests/ThreadSafeHeadersTests.cs +++ b/test/Ocelot.IntegrationTests/ThreadSafeHeadersTests.cs @@ -119,7 +119,7 @@ private static void GivenThereIsAConfiguration(FileConfiguration fileConfigurati { var configurationPath = $"{Directory.GetCurrentDirectory()}/ocelot.json"; - var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsFactory.Web); + var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, OcelotSerializerOptions.Web); if (File.Exists(configurationPath)) { diff --git a/test/Ocelot.ManualTest/CustomOcelotMiddleware.cs b/test/Ocelot.ManualTest/CustomOcelotMiddleware.cs index c55100e08..d8654fb62 100644 --- a/test/Ocelot.ManualTest/CustomOcelotMiddleware.cs +++ b/test/Ocelot.ManualTest/CustomOcelotMiddleware.cs @@ -17,7 +17,7 @@ public static Task Invoke(HttpContext context, Func next) { logger.LogInformation(() => { - var metadataInJson = JsonSerializer.Serialize(metadata, JsonSerializerOptionsFactory.Web); + var metadataInJson = JsonSerializer.Serialize(metadata, OcelotSerializerOptions.Web); var message = $"My custom middleware found some metadata: {metadataInJson}"; return message; }); diff --git a/test/Ocelot.UnitTests/Configuration/DiskFileConfigurationRepositoryTests.cs b/test/Ocelot.UnitTests/Configuration/DiskFileConfigurationRepositoryTests.cs index 2ab45ac91..ef5e444ba 100644 --- a/test/Ocelot.UnitTests/Configuration/DiskFileConfigurationRepositoryTests.cs +++ b/test/Ocelot.UnitTests/Configuration/DiskFileConfigurationRepositoryTests.cs @@ -157,14 +157,14 @@ private void ThenTheConfigurationIsStoredAs(FileConfiguration expecteds) private static void ThenTheOcelotJsonIsStoredAs(FileInfo ocelotJson, FileConfiguration expecteds) { var actual = File.ReadAllText(ocelotJson.FullName); - var expectedText = JsonSerializer.Serialize(expecteds, JsonSerializerOptionsFactory.WebWriteIndented); + var expectedText = JsonSerializer.Serialize(expecteds, OcelotSerializerOptions.WebWriteIndented); actual.ShouldBe(expectedText); } private void GivenTheConfigurationIs(FileConfiguration fileConfiguration, [CallerMemberName] string environmentName = null) { var environmentSpecificPath = Path.Combine(TestID, string.Format(ConfigurationBuilderExtensions.EnvironmentConfigFile, environmentName)); - var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, JsonSerializerOptionsFactory.WebWriteIndented); + var jsonConfiguration = JsonSerializer.Serialize(fileConfiguration, OcelotSerializerOptions.WebWriteIndented); var environmentSpecific = new FileInfo(environmentSpecificPath); if (environmentSpecific.Exists) { @@ -179,7 +179,7 @@ private void ThenTheConfigurationJsonIsIndented(FileConfiguration expecteds, [Ca { var environmentSpecific = Path.Combine(TestID, string.Format(ConfigurationBuilderExtensions.EnvironmentConfigFile, environmentName)); var actual = File.ReadAllText(environmentSpecific); - var expectedText = JsonSerializer.Serialize(expecteds, JsonSerializerOptionsFactory.WebWriteIndented); + var expectedText = JsonSerializer.Serialize(expecteds, OcelotSerializerOptions.WebWriteIndented); actual.ShouldBe(expectedText); _files.Add(environmentSpecific); } diff --git a/test/Ocelot.UnitTests/Consul/ConsulFileConfigurationRepositoryTests.cs b/test/Ocelot.UnitTests/Consul/ConsulFileConfigurationRepositoryTests.cs index b8b5bf5c5..d10b8cdcf 100644 --- a/test/Ocelot.UnitTests/Consul/ConsulFileConfigurationRepositoryTests.cs +++ b/test/Ocelot.UnitTests/Consul/ConsulFileConfigurationRepositoryTests.cs @@ -142,8 +142,8 @@ private void GivenTheConfigKeyComesFromFileConfig(string key) private void ThenTheConfigurationIs(FileConfiguration config) { - var expected = JsonSerializer.Serialize(config, JsonSerializerOptionsFactory.WebWriteIndented); - var result = JsonSerializer.Serialize(_getResult.Data, JsonSerializerOptionsFactory.WebWriteIndented); + var expected = JsonSerializer.Serialize(config, OcelotSerializerOptions.WebWriteIndented); + var result = JsonSerializer.Serialize(_getResult.Data, OcelotSerializerOptions.WebWriteIndented); result.ShouldBe(expected); } @@ -170,7 +170,7 @@ private void GivenFetchFromConsulReturnsNull() private void GivenFetchFromConsulSucceeds() { - var json = JsonSerializer.Serialize(_fileConfiguration, JsonSerializerOptionsFactory.WebWriteIndented); + var json = JsonSerializer.Serialize(_fileConfiguration, OcelotSerializerOptions.WebWriteIndented); var bytes = Encoding.UTF8.GetBytes(json); var kvp = new KVPair("OcelotConfiguration") { @@ -186,7 +186,7 @@ private void GivenFetchFromConsulSucceeds() private void ThenTheConfigurationIsStoredAs(FileConfiguration config) { - var json = JsonSerializer.Serialize(config, JsonSerializerOptionsFactory.WebWriteIndented); + var json = JsonSerializer.Serialize(config, OcelotSerializerOptions.WebWriteIndented); var bytes = Encoding.UTF8.GetBytes(json); _kvEndpoint.Verify(x => x.Put(It.Is(k => k.Value.SequenceEqual(bytes)), It.IsAny()), Times.Once); } diff --git a/test/Ocelot.UnitTests/Consul/ConsulTests.cs b/test/Ocelot.UnitTests/Consul/ConsulTests.cs index c3f1d14c4..7fb6ff18b 100644 --- a/test/Ocelot.UnitTests/Consul/ConsulTests.cs +++ b/test/Ocelot.UnitTests/Consul/ConsulTests.cs @@ -205,7 +205,7 @@ private void GivenThereIsAFakeConsulServiceDiscoveryProvider([CallerMemberName] _receivedToken = values.First(); } - var json = JsonSerializer.Serialize(_consulServiceEntries, JsonSerializerOptionsFactory.Web); + var json = JsonSerializer.Serialize(_consulServiceEntries, OcelotSerializerOptions.Web); context.Response.Headers.Append("Content-Type", "application/json"); await context.Response.WriteAsync(json); } diff --git a/test/Ocelot.UnitTests/DependencyInjection/ConfigurationBuilderExtensionsTests.cs b/test/Ocelot.UnitTests/DependencyInjection/ConfigurationBuilderExtensionsTests.cs index 4736f268b..dc0b87bc5 100644 --- a/test/Ocelot.UnitTests/DependencyInjection/ConfigurationBuilderExtensionsTests.cs +++ b/test/Ocelot.UnitTests/DependencyInjection/ConfigurationBuilderExtensionsTests.cs @@ -189,7 +189,7 @@ private void GivenMultipleConfigurationFiles(string folder, bool withEnvironment foreach (var part in configParts) { var filename = Path.Combine(folder, string.Format(ConfigurationBuilderExtensions.EnvironmentConfigFile, part.Key)); - File.WriteAllText(filename, JsonSerializer.Serialize(part.Value, JsonSerializerOptionsFactory.WebWriteIndented)); + File.WriteAllText(filename, JsonSerializer.Serialize(part.Value, OcelotSerializerOptions.WebWriteIndented)); _files.Add(filename); } } diff --git a/test/Ocelot.UnitTests/Kubernetes/KubeTests.cs b/test/Ocelot.UnitTests/Kubernetes/KubeTests.cs index 83d427ade..1ee689e82 100644 --- a/test/Ocelot.UnitTests/Kubernetes/KubeTests.cs +++ b/test/Ocelot.UnitTests/Kubernetes/KubeTests.cs @@ -161,7 +161,7 @@ Task ProcessKubernetesRequest(HttpContext context) token = values.First(); } - var json = JsonSerializer.Serialize(endpointEntries, JsonSerializerOptionsFactory.Web); + var json = JsonSerializer.Serialize(endpointEntries, OcelotSerializerOptions.Web); context.Response.Headers.Append("Content-Type", "application/json"); return context.Response.WriteAsync(json); } diff --git a/test/Ocelot.UnitTests/JsonSerializerOptionsFactoryTests.cs b/test/Ocelot.UnitTests/OcelotSerializerOptionsTests.cs similarity index 97% rename from test/Ocelot.UnitTests/JsonSerializerOptionsFactoryTests.cs rename to test/Ocelot.UnitTests/OcelotSerializerOptionsTests.cs index 9e00d5fcc..a488393bc 100644 --- a/test/Ocelot.UnitTests/JsonSerializerOptionsFactoryTests.cs +++ b/test/Ocelot.UnitTests/OcelotSerializerOptionsTests.cs @@ -3,7 +3,7 @@ namespace Ocelot.UnitTests; -public class JsonSerializerOptionsFactoryTests : UnitTest +public class OcelotSerializerOptionsTests : UnitTest { [Fact] public void should_json_path()