dotnet / dotnet/aspnetcore

Type disciminator is missing with OkResult

Open
#58,832 9 comments 2 reactions 1 assignee Claimed by @mikekistler View on GitHub
area-mvc
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 10h
Merged PRs (30d)
281

Description

### Is there an existing issue for this?

- [x] I have searched the existing issues

### Describe the bug

I am using polymorphic JSON which works when returning the class but not when returning `Ok(data)` because then the `$type` type discriminator is missing.

Works:
```cs
[HttpGet(Name = "Pet")]
public ActionResult Get()
{
return new Cat() { CatName = "Mizzy" };
}
```

Does not work:
```cs
[HttpGet(Name = "Pet")]
public ActionResult Get()
{
return Ok(new Cat() { CatName = "Mizzy" });
}
```

Also does not work:
```cs
[HttpGet(Name = "Pet")]
public ActionResult Get()
{
return Ok(new Cat() { CatName = "Mizzy" } as BaseModel);
}
```

### Expected Behavior

When using the `Ok` method to return a `OkObjectResult` it should output a type discriminator.

### Steps To Reproduce

```cs
using Microsoft.AspNetCore.Mvc;
using System.Text.Json.Serialization;

namespace WebApplication1.Controllers
{
[ApiController]
[Route("[controller]")]
public class ExampleController : ControllerBase
{
[HttpGet(Name = "GetPet")]
public ActionResult Get()
{
return Ok(new Cat() { CatName = "Mizzy" } as BaseModel);
}
}

[JsonPolymorphic]
[JsonDerivedType(typeof(Cat), "cat")]
[JsonDerivedType(typeof(Dog), "dog")]
public class BaseModel
{
public string Name { get; set; }
}

public class Cat : BaseModel
{
public string CatName { get; set; }
}

class Dog : BaseModel
{
public string DogName { get; set; }
}
}
```

### Exceptions (if any)

_No response_

### .NET Version

8.0.10

### Anything else?

_No response_

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.