Introduce generic JsonResult<T>
#55535
Labels
api-suggestion
Early API idea and discussion, it is NOT ready for implementation
area-web-frameworks
Background and Motivation
Currently in
System.Text.Json
we haveJsonSerializer.Serialize<T>(...)
that serializes an object "as T". Which means, if we cast an object to some base class, or to an interface - the serializer will use that exact casted type's properties etc..HOWEVER the AspNetCore
JsonResult
works differently. When it serializes an object, it always takes the object's hard type. See the source here: https://source.dot.net/#Microsoft.AspNetCore.Mvc.Core/Infrastructure/SystemTextJsonResultExecutor.cs,61 which means that even if we cast the object to something - nah, it does not care, it just uses the actual type.As a workaround, people either use
JsonSerializer.Serialize<T>
to serialize to intermediate string and then return content (not optimal since it buffers everything into a huge string before sending to the client). Or - people write their ownJsonResult<T>
that handles this (tat's what I did)Proposed API
Disclaimer: this is just the code I use as a workaround, it's very simple, and misses stuff, but just to give the idea...
Usage Examples
Alternative Designs
Another option would e to somehow pass the
type
to existingJsonResult
The text was updated successfully, but these errors were encountered: