ardalis / Result

A result abstraction that can be mapped to HTTP response codes if needed.
MIT License
872 stars 107 forks source link

Type discriminator is lost when serializing a Result<T> using [TranslateResultToActionResult] #204

Open uflowie opened 1 month ago

uflowie commented 1 month ago

When serializing a derived type as its base type, System.Text.Json will use an extra type discriminator field to communicate the actual type of the serialized data. Given a base class Base and a derived type Derived, I have observed the following behavior:

  1. A controller endpoint returning Base will correctly include the type discriminator.
  2. A controller endpoint returning ActionResult<Base> will include the type discriminator.
  3. A controller endpoint returning Result<Base> will include the properties of the derived type but it will NOT include the type discriminator.

Minimal reproducible example: https://github.com/uflowie/ResultLostTypeDiscriminator

ardalis commented 1 month ago

Is this causing a real world problem? Your controllers should typically never return just an object and not an ActionRest, in order to support NotFound, etc.

uflowie commented 1 month ago

Our controllers aren't returning just an object, they are returning a Result. But since the type discriminator for T is lost (unlike if I returned T directly), I cannot have polymorphic endpoints returning Result

ardalis commented 1 month ago

Right but based on what you're writing above, if they returned ActionResult<Result<T>> everything would work correctly.

uflowie commented 1 month ago

ActionResult<Result<T>> does not work either, only ActionResult<T>