Description
Background and Motivation
Both JsonSerializer
and Http[Request/Response]Extensions
provide AOT/Trimmer-safe overloads, with JsonTypeInfo
or JsonSerializerContext
, however, when producing a Json response using the static [Typed]Results
class only overloads that take JsonSerializerOptions are available.
My suggestion is introduced new overload, following the same available in the JsonSerializer
and Http[Request/Response]Extensions
and mark the current overload with RUC/RDC
attributes.
Proposed API
namespace Microsoft.AspNetCore.Http;
public static class TypedResults
{
public static JsonHttpResult<TValue> Json<TValue>(TValue? data, JsonSerializerOptions? options = null, string? contentType = null, int? statusCode = null)
+ public static JsonHttpResult<TValue> Json<TValue>(TValue? data, JsonSerializerContext jsonContext, string? contentType = null, int? statusCode = null) {}
+ public static JsonHttpResult<TValue> Json<TValue>(TValue? data, JsonTypeInfo jsonTypeInfo, string? contentType = null, int? statusCode = null)
}
public static class Results
{
public static IResult Json<TValue>(TValue? data, JsonSerializerOptions? options = null, string? contentType = null, int? statusCode = null)
+ public static IResult Json<TValue>(TValue? data, JsonSerializerContext jsonSerializerContext, string? contentType = null, int? statusCode = null) {}
+ public static IResult Json<TValue>(TValue? data, JsonTypeInfo jsonTypeInfo, string? contentType = null, int? statusCode = null){}
public static IResult Json(object? data, JsonSerializerOptions? options = null, string? contentType = null, int? statusCode = null)
+ public static IResult Json(object? data, JsonSerializerContext jsonSerializerContext, string? contentType = null, int? statusCode = null){}
+ public static IResult Json(object? data, JsonTypeInfo jsonTypeInfo, string? contentType = null, int? statusCode = null){}
}
Usage Examples
using System.Text.Json.Serialization;
var app = WebApplication.Create(args);
// Using context
app.MapGet("/", () => TypedResults.Json(new Sample(), SampleJsonContext.Default));
// Using typeInfo
app.MapGet("/", () => TypedResults.Json(new Sample(), SampleJsonContext.Default.Sample));
app.Run();
public class Sample
{ }
[JsonSerializable(typeof(Sample))]
public partial class SampleJsonContext : JsonSerializerContext
{ }
Alternative Designs
Should MVC controller base be updated as well?
Risks
[Type]Results
already have few overloads for the Json
methods, that introducing those new overloads will cause ambiguity when calling something like Json(new Sample(), null, contentType, statusCode)
but it is similar to what JsonSerializer
method have today