Skip to content

Set default JSON type resolver if not set #49393

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jul 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions src/Http/Http.Extensions/test/RequestDelegateFactoryTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
using Microsoft.AspNetCore.Http.Metadata;
using Microsoft.AspNetCore.Routing.Patterns;
using Microsoft.AspNetCore.Testing;
using Microsoft.DotNet.RemoteExecutor;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Internal;
using Microsoft.Extensions.Logging;
Expand Down Expand Up @@ -2903,6 +2904,44 @@ static void TestAction([AsParameters] ParameterListMixedRequiredStringsFromDiffe
}
#nullable enable

[ConditionalFact]
[RemoteExecutionSupported]
public void RequestDelegateFactory_WhenJsonIsReflectionEnabledByDefaultFalse()
{
var options = new RemoteInvokeOptions();
options.RuntimeConfigurationOptions.Add("System.Text.Json.JsonSerializer.IsReflectionEnabledByDefault", false.ToString());

using var remoteHandle = RemoteExecutor.Invoke(static () =>
{
// Arrange
var @delegate = (string task) => new Todo();

// IsReflectionEnabledByDefault defaults to `false` when `PublishTrimmed=true`. For these scenarios, we
// expect users to configure JSON source generation as instructed in the `NotSupportedException` message.
var exception = Assert.Throws<NotSupportedException>(() => RequestDelegateFactory.Create(@delegate));
Assert.Contains("Microsoft.AspNetCore.Routing.Internal.RequestDelegateFactoryTests+Todo", exception.Message);
Assert.Contains("JsonSerializableAttribute", exception.Message);
}, options);
}

[ConditionalFact]
[RemoteExecutionSupported]
public void RequestDelegateFactory_WhenJsonIsReflectionEnabledByDefaultTrue()
{
var options = new RemoteInvokeOptions();
options.RuntimeConfigurationOptions.Add("System.Text.Json.JsonSerializer.IsReflectionEnabledByDefault", true.ToString());

using var remoteHandle = RemoteExecutor.Invoke(static () =>
{
// Arrange
var @delegate = (string task) => new Todo();

// Assert
var exception = Record.Exception(() => RequestDelegateFactory.Create(@delegate));
Assert.Null(exception);
}, options);
}

private DefaultHttpContext CreateHttpContext()
{
var responseFeature = new TestHttpResponseFeature();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ public SystemTextJsonOutputFormatter(JsonSerializerOptions jsonSerializerOptions
{
SerializerOptions = jsonSerializerOptions;

// Use JsonTypeInfoResolver.Combine() to produce an empty TypeInfoResolver
jsonSerializerOptions.TypeInfoResolver ??= JsonTypeInfoResolver.Combine();
jsonSerializerOptions.MakeReadOnly();

SupportedEncodings.Add(Encoding.UTF8);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
using Microsoft.AspNetCore.Testing;
using Microsoft.DotNet.RemoteExecutor;
using Microsoft.Extensions.Primitives;
using Microsoft.Net.Http.Headers;

Expand Down Expand Up @@ -254,13 +256,39 @@ private static async IAsyncEnumerable<JsonPerson> GetPeopleAsync()
}

[Fact]
public void WriteResponseBodyAsync_Throws_WhenTypeResolverIsNull()
public void WriteResponseBodyAsync_Works_WhenTypeResolverIsNull()
{
// Arrange
var jsonOptions = new JsonOptions();
jsonOptions.JsonSerializerOptions.TypeInfoResolver = null;

Assert.Throws<InvalidOperationException>(() => SystemTextJsonOutputFormatter.CreateFormatter(jsonOptions));
var stjOutputFormatter = SystemTextJsonOutputFormatter.CreateFormatter(jsonOptions);
Assert.IsAssignableFrom<IJsonTypeInfoResolver>(stjOutputFormatter.SerializerOptions.TypeInfoResolver);
}

[ConditionalTheory]
[RemoteExecutionSupported]
[InlineData(false)]
[InlineData(true)]
public void STJOutputFormatter_UsesEmptyResolver_WhenJsonIsReflectionEnabledByDefaultFalse(bool isReflectionEnabledByDefault)
{
var options = new RemoteInvokeOptions();
options.RuntimeConfigurationOptions.Add("System.Text.Json.JsonSerializer.IsReflectionEnabledByDefault", isReflectionEnabledByDefault.ToString());

using var remoteHandle = RemoteExecutor.Invoke(static () =>
{
// Arrange
var jsonOptions = new JsonOptions();

// Assert
var stjOutputFormatter = SystemTextJsonOutputFormatter.CreateFormatter(jsonOptions);
Assert.IsAssignableFrom<IJsonTypeInfoResolver>(stjOutputFormatter.SerializerOptions.TypeInfoResolver);
// Use default resolver if reflection is enabled instead of empty one
if (JsonSerializer.IsReflectionEnabledByDefault)
{
Assert.IsType<DefaultJsonTypeInfoResolver>(stjOutputFormatter.SerializerOptions.TypeInfoResolver);
}
}, options);
}

private class Person
Expand Down
2 changes: 2 additions & 0 deletions src/Shared/Json/JsonSerializerExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ public static bool ShouldUseWith(this JsonTypeInfo jsonTypeInfo, [NotNullWhen(fa

public static JsonTypeInfo GetReadOnlyTypeInfo(this JsonSerializerOptions options, Type type)
{
// Use JsonTypeInfoResolver.Combine() to produce an empty TypeInfoResolver
options.TypeInfoResolver ??= JsonTypeInfoResolver.Combine();
options.MakeReadOnly();
return options.GetTypeInfo(type);
}
Expand Down