dotnet / dotnet/aspnetcore

[FromForm]: Support for Polymorphic Types

Open
#61,378 1 comment 0 reactions 0 assignees View on GitHub
area-mvc
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 5h
Merged PRs (30d)
276

Description

### Is there an existing issue for this?

- [x] I have searched the existing issues

### Describe the bug

Consider the below POCO classes:
```csharp
public class SomeHttpRequestModel
{
public OptionsBase Options { get; set; }
}

[JsonDerivedType(typeof(ClassificationOptions), nameof(ClassificationOptions))]
[JsonDerivedType(typeof(AnalyzeOptions), nameof(AnalyzeOptions))]
public class OptionsBase
{
public string? CommonOption1 { get; set; } = null;
}

public class ClassificationOptions : OptionsBase
{
public string? ClassificationOption1 { get; set; } = null;
}

public class AnalyzeOptions : OptionsBase
{
public string? AnalyzeOption1 { get; set; } = null;
}
```
Now I have the following Controller.
```csharp
[ApiController]
[Route("[controller]")]
public class ValuesController : ControllerBase
{
[HttpPost("/FromBody", Name = "PostFromBody")]
public IActionResult PostFromBody([FromBody] SomeHttpRequestModel someHttpRequestModel)
{
return Ok(someHttpRequestModel);
}

[HttpPost("/FromForm", Name = "PostFromForm")]
public IActionResult PostFromForm([FromForm] SomeHttpRequestModel someHttpRequestModel)
{
return Ok(someHttpRequestModel);
}
}
```
Now when I call `/FromBody`,
```
@WebApplication1_HostAddress = http://localhost:5001

POST {{WebApplication1_HostAddress}}/FromBody/
Content-Type: application/json

{
"options": {
"$type": "ClassificationOptions",
"commonOption1": "SomeCommonOption1",
"classificationOption1": "someClassificationOption1"
}
}
```
It's deserializing as expected.
![Image](https://github.com/user-attachments/assets/954d3a13-4613-4323-85b9-32ce86fe9569)

Now when I call `/FromForm`,
```curl
curl --location 'http://localhost:5001/FromForm' `
--form 'options.$type="ClassificationOptions"' `
--form 'options.commonOption1="SomeCommonOption1"' `
--form 'options.classificationOption1="SomeClassificationOption1"'
```
It's not getting deserialized correctly.

![Image](https://github.com/user-attachments/assets/e976fd92-8163-47cd-845f-810bd8db982d)

### Expected Behavior

`FromForm` should use same deserialization as `FromBody`

### Steps To Reproduce

[https://github.com/jaliyaudagedara/aspnetcore-minimal-repros/tree/main/fromform-jsonderivedtypes](https://github.com/jaliyaudagedara/aspnetcore-minimal-repros/tree/main/fromform-jsonderivedtypes)

### Exceptions (if any)

_No response_

### .NET Version

10.0.100-preview.2.25164.34

### 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.