Allow to specify type to serialize in SystemTextJsonOutputFormatter #41399
Labels
area-mvc
Includes: MVC, Actions and Controllers, Localization, CORS, most templates
Milestone
Uh oh!
There was an error while loading. Please reload this page.
Is there an existing issue for this?
Is your feature request related to a problem? Please describe the problem.
I'm trying to specify what type the
SystemTextJsonOutputFormatter
should serialize, but it's not possible, because it goes out of its way to use the actual type of the value.Let's consider code like this:
In all cases above, the value is serialized as
Child
and notParent
. In fact there seems to be no way to serialize it asParent
.This is because of code in
SystemTextJsonOutputFormatter
aspnetcore/src/Mvc/Mvc.Core/src/Formatters/SystemTextJsonOutputFormatter.cs
Lines 73 to 77 in f9ae0f5
I understand the sentiment. As the comment says, you want to be compatible with NewtonsoftJson at least at the root level. But I think it goes too far and hope that there can be a way added to specify the type for serialization.
I think the comment: "context.ObjectType reflects the declared model type when specified" is inaccurate. In case of simple return type (
Parent Get() {}
), theObjectType
property is in fact set to the runtime type of the instance due to code inOutputResultExecutor
:aspnetcore/src/Mvc/Mvc.Core/src/Infrastructure/ObjectResultExecutor.cs
Lines 89 to 94 in 6d21cf1
Describe the solution you'd like
I understand that there's slim chance you'll change the existing behavior, because it will be a breaking change. But anyway, I'd like the cases where
ObjectResult
specifies theDeclaredType
to pass that type to the STJ serializer. That means that in the example code above, second and third cases should serialize the value asParent
and notChild
.Additional context
I stumbled upon this problem when analyzing some code that directly returns EF entities out of MVC actions. The entity used virtual property for lazy loading support. The property was decorated with
JsonIgnore
attribute, but it didn't work.The analysis showed that Mvc passes the EF-generated proxy type to STJ and STJ doesn't read inherited attributes (
GetCustomAttributes(..., inherit: false)
. The end result is that lazy loaded property was getting serialized while the intention was to ignore it.The text was updated successfully, but these errors were encountered: