Skip to content

[FromForm]: Support for Polymorphic Types #61378

Open
@jaliyaudagedara

Description

@jaliyaudagedara

Is there an existing issue for this?

  • I have searched the existing issues

Describe the bug

Consider the below POCO classes:

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.

[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

Now when I call /FromForm,

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

Expected Behavior

FromForm should use same deserialization as FromBody

Steps To Reproduce

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-mvcIncludes: MVC, Actions and Controllers, Localization, CORS, most templates

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions