Skip to content

Adding Http(Request/Response) extension methods overloads accepting non-generic JsonTypeInfo #45568

Closed
@brunolins16

Description

@brunolins16

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>.

return HttpResponseJsonExtensions.WriteAsJsonAsync(response, value, value is null ? typeof(object) : value.GetType(), options, default);

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.

https://github.com/davidfowl/uController/blob/86fe16e634bdc34e641c3d983a3f26bba80ccebe/GeneratedOutput/RouteBuilderExtensions.g.cs#L504

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

cc @eiriktsarpalis

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-approvedAPI was approved in API review, it can be implementedold-area-web-frameworks-do-not-use*DEPRECATED* This label is deprecated in favor of the area-mvc and area-minimal labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions