Closed
Description
Background and Motivation
STJ introduced new overloads (dotnet/runtime#77051) with untyped JsonTypeInfo
, however, HttpResponse
and HttpRequest
extension methods only support JsonTypeInfo<T>
.
As part of the work to make ASP.NET Core AOT-friendly, we have a need of those methods available. As an example, RDF needs to write the JSON response based on the runtime type and cannot create a typed JsonTypeInfo<T>
.
Same for the uController
source generator rely on the HttpResponse
extensions to write a JSON content and might not be able to have a generic JsonTypeInfo
.
Proposed API
namespace Microsoft.AspNetCore.Http;
public static class HttpResponseJsonExtensions
{
+ public static Task WriteAsJsonAsync(
+ this HttpResponse response,
+ object? value,
+ JsonTypeInfo jsonTypeInfo,
+ string? contentType = default,
+ CancellationToken cancellationToken = default);
}
namespace Microsoft.AspNetCore.Http;
public static class HttpRequestJsonExtensions
{
+ public static ValueTask<object?> ReadFromJsonAsync(
+ this HttpRequest request,
+ JsonTypeInfo jsonTypeInfo,
+ CancellationToken cancellationToken = default);
}
Usage Examples
ValueTask<object?> ReadBody(HttpContext context, Type bodyType, JsonSerializerOptions jsonSerializerOptions)
{
var bodyJsonTypeInfo = jsonSerializerOptions.GetTypeInfo(bodyType);
return httpContext.Request.ReadFromJsonAsync(bodyJsonTypeInfo);
}
Task WriteResponse(HttpContext context, object? value, JsonSerializerOptions jsonSerializerOptions)
{
var runtimeType = value is null ? typeof(object) : value.GetType();
var runtimeTypeInfo = jsonSerializerOptions.GetTypeInfo(runtimeType);
return httpContext.Response.WriteAsJsonAsync(value, runtimeTypeInfo );
}
Alternative Designs
No response
Risks
No response