Skip to content

Support STJ Polymorphism #45405

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 31 commits into from
Jan 10, 2023
Merged
Show file tree
Hide file tree
Changes from 30 commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
7cc182d
Initial GetTypeInfo usage
brunolins16 Nov 29, 2022
69ecc80
Merging 45359
brunolins16 Nov 30, 2022
fb1fabb
Using TypeInfoAPI
brunolins16 Dec 1, 2022
a2473bb
Merge branch 'main' into brunolins16/issues/44852
brunolins16 Dec 1, 2022
2eac02f
Updating comments
brunolins16 Dec 1, 2022
59e9b6e
Remove using
brunolins16 Dec 1, 2022
1e05325
Updating MVC support
brunolins16 Dec 2, 2022
044d219
Adding fastpath
brunolins16 Dec 2, 2022
0b7940f
Trying to fix mvc
brunolins16 Dec 2, 2022
32d7cf4
Updating mvc support
brunolins16 Dec 2, 2022
16f37f9
Simplify MVC
brunolins16 Dec 2, 2022
784d364
Moving more to fastpath
brunolins16 Dec 3, 2022
62edd21
Adding JsonOptions setup
brunolins16 Dec 9, 2022
5586708
Moving DefaultJsonTypeInfoResolver instance creation
brunolins16 Dec 9, 2022
d37a9c6
Merge branch 'main' into brunolins16/issues/44852
brunolins16 Dec 9, 2022
19b54b6
Fix bad merge
brunolins16 Dec 9, 2022
5f76c1b
Adding RDF unit tests
brunolins16 Dec 10, 2022
7657b25
Adding more RDF tests
brunolins16 Dec 10, 2022
c3f98bf
Adding MVC unit tests
brunolins16 Dec 12, 2022
e4eb4bd
Updating IL2026 warnings
brunolins16 Dec 12, 2022
84b7eb5
Scoping trimming warning
brunolins16 Dec 12, 2022
ca3809f
Updates
brunolins16 Dec 15, 2022
2c64c14
Merge remote-tracking branch 'upstream/main' into brunolins16/issues/…
brunolins16 Dec 15, 2022
6e87830
Changing to always JsonTypeInfo
brunolins16 Dec 16, 2022
7c6ef7c
Merge remote-tracking branch 'upstream/main' into brunolins16/issues/…
brunolins16 Jan 3, 2023
3e136b4
Adding JsonSerializerExtensions
brunolins16 Jan 3, 2023
bc162e6
Fixing warnings
brunolins16 Jan 3, 2023
0bdfb96
Apply suggestions from code review
brunolins16 Jan 5, 2023
71bb5b6
Updating suppression
brunolins16 Jan 5, 2023
534c62c
Adding IL3050
brunolins16 Jan 5, 2023
45bbd69
Merge remote-tracking branch 'upstream/main' into brunolins16/issues/…
brunolins16 Jan 9, 2023
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
44 changes: 44 additions & 0 deletions src/Http/Http.Extensions/src/HttpResponseJsonExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,50 @@ static async Task WriteAsJsonAsyncSlow(HttpResponse response, TValue value, Json
}
}

/// <summary>
/// Write the specified value as JSON to the response body. The response content-type will be set to
/// the specified content-type.
/// </summary>
/// <param name="response">The response to write JSON to.</param>
/// <param name="value">The value to write as JSON.</param>
/// <param name="jsonTypeInfo">Metadata about the type to convert.</param>
/// <param name="contentType">The content-type to set on the response.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> used to cancel the operation.</param>
/// <returns>The task object representing the asynchronous operation.</returns>
#pragma warning disable RS0026 // Do not add multiple public overloads with optional parameters
internal static Task WriteAsJsonAsync(
#pragma warning restore RS0026 // Do not add multiple public overloads with optional parameters
this HttpResponse response,
object? value,
JsonTypeInfo jsonTypeInfo,
string? contentType = default,
CancellationToken cancellationToken = default)
{
if (response == null)
{
throw new ArgumentNullException(nameof(response));
}

response.ContentType = contentType ?? JsonConstants.JsonContentTypeWithCharset;

// if no user provided token, pass the RequestAborted token and ignore OperationCanceledException
if (!cancellationToken.CanBeCanceled)
{
return WriteAsJsonAsyncSlow(response, value, jsonTypeInfo);
}

return JsonSerializer.SerializeAsync(response.Body, value, jsonTypeInfo, cancellationToken);

static async Task WriteAsJsonAsyncSlow(HttpResponse response, object? value, JsonTypeInfo jsonTypeInfo)
{
try
{
await JsonSerializer.SerializeAsync(response.Body, value, jsonTypeInfo, response.HttpContext.RequestAborted);
}
catch (OperationCanceledException) { }
}
}

[RequiresUnreferencedCode(RequiresUnreferencedCodeMessage)]
private static async Task WriteAsJsonAsyncSlow<TValue>(
Stream body,
Expand Down
13 changes: 13 additions & 0 deletions src/Http/Http.Extensions/src/JsonOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Serialization.Metadata;

#nullable enable

Expand All @@ -21,11 +22,23 @@ public class JsonOptions
// Because these options are for producing content that is written directly to the request
// (and not embedded in an HTML page for example), we can use UnsafeRelaxedJsonEscaping.
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,

// The JsonSerializerOptions.GetTypeInfo method is called directly and needs a defined resolver
// setting the default resolver (reflection-based) but the user can overwrite it directly or calling
Copy link
Member

@eiriktsarpalis eiriktsarpalis Dec 15, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Given that this is a global instance, I would recommend making it read-only from the get-go using the JsonSerializerOptions.MakeReadOnly() method.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe that here is too early to do this. Users still have a chance to chance the options at this point

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This will makes the code susceptible to races, in which multiple threads try to set potentially conflicting configuration to the same singleton.

// .AddContext<TContext>()
TypeInfoResolver = CreateDefaultTypeResolver()
};

// Use a copy so the defaults are not modified.
/// <summary>
/// Gets the <see cref="JsonSerializerOptions"/>.
/// </summary>
public JsonSerializerOptions SerializerOptions { get; } = new JsonSerializerOptions(DefaultSerializerOptions);

#pragma warning disable IL2026 // Suppressed in Microsoft.AspNetCore.Http.Extensions.WarningSuppressions.xml
#pragma warning disable IL3050 // Calling members annotated with 'RequiresDynamicCodeAttribute' may break functionality when AOT compiling.
private static IJsonTypeInfoResolver CreateDefaultTypeResolver()
=> new DefaultJsonTypeInfoResolver();
#pragma warning restore IL3050 // Calling members annotated with 'RequiresDynamicCodeAttribute' may break functionality when AOT compiling.
#pragma warning restore IL2026 // Suppressed in Microsoft.AspNetCore.Http.Extensions.WarningSuppressions.xml
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<linker>
<assembly fullname="Microsoft.AspNetCore.Http.Extensions, Version=8.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60">
<attribute fullname="System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute">
<argument>ILLink</argument>
<argument>IL2026</argument>
<property name="Scope">member</property>
<property name="Target">M:Microsoft.AspNetCore.Http.Json.JsonOptions.CreateDefaultTypeResolver</property>
<property name="Justification">This warning is left in the product so developers get an ILLink warning when trimming an app, in future, only when Microsoft.AspNetCore.EnsureJsonTrimmability=false.</property>
</attribute>
</assembly>
</linker>
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@
<Compile Include="$(SharedSourceRoot)RoutingMetadata\AcceptsMetadata.cs" LinkBase="Shared" />
<Compile Include="$(SharedSourceRoot)TypeNameHelper\TypeNameHelper.cs" LinkBase="Shared"/>
<Compile Include="$(SharedSourceRoot)ProblemDetails\ProblemDetailsDefaults.cs" LinkBase="Shared" />
<Compile Include="$(SharedSourceRoot)ValueStringBuilder\**\*.cs" LingBase="Shared"/>
<Compile Include="$(SharedSourceRoot)ValueStringBuilder\**\*.cs" LinkBase="Shared"/>
<Compile Include="$(SharedSourceRoot)Json\JsonSerializerExtensions.cs" LinkBase="Shared"/>
</ItemGroup>

<ItemGroup>
Expand Down
Loading