Skip to content

Dictionary model binding behaves different with Enum as Key vs Value #50748

@wadeamaral

Description

@wadeamaral

Is there an existing issue for this?

  • I have searched the existing issues

Describe the bug

Consider the following example:

[ApiController]
[Route("[controller]")]
public class TestController : ControllerBase
{

    [HttpGet]
    [Route("key")]
    public IActionResult KeyTest([FromQuery] Dictionary<TestEnum, string> prop)
    {
        return Ok();
    }

    [HttpGet]
    [Route("value")]
    public IActionResult ValueTest([FromQuery] Dictionary<string, TestEnum> prop)
    {
        return Ok();
    }
}

public enum TestEnum
{
    EnumVal1,
    EnumVal2
}

The following requests produce the 200 response and a populated dictionary:

/Test/key?Prop[enumval1]=string
/Test/value?Prop[string]=enumval1

The following request produces an invalid modelstate with a 400 response:

/Test/value?Prop[string]=badEnum

The following request produces an internal server error:

/Test/key?Prop[badEnum]=string

The stack trace shows the following error:

System.FormatException: badEnum is not a valid value for TestEnum.
 ---> System.ArgumentException: Requested value 'badEnum' was not found.
   at System.Enum.TryParseByName(RuntimeType enumType, ReadOnlySpan`1 value, Boolean ignoreCase, Boolean throwOnFailure, UInt64& result)
   at System.Enum.TryParseInt32Enum(RuntimeType enumType, ReadOnlySpan`1 value, Int32 minInclusive, Int32 maxInclusive, Boolean ignoreCase, Boolean throwOnFailure, TypeCode type, Int32& result)
   at System.Enum.TryParse(Type enumType, ReadOnlySpan`1 value, Boolean ignoreCase, Boolean throwOnFailure, Object& result)
   at System.Enum.Parse(Type enumType, String value, Boolean ignoreCase)
   at System.ComponentModel.EnumConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value)
   --- End of inner exception stack trace ---

Is there a reason for the difference in binding behavior? Is it possible to have the Dictionary<TestEnum, string> produce a model state error instead of throwing a FormatException?

Expected Behavior

No response

Steps To Reproduce

No response

Exceptions (if any)

No response

.NET Version

No response

Anything else?

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-mvcIncludes: MVC, Actions and Controllers, Localization, CORS, most templatesbugThis issue describes a behavior which is not expected - a bug.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions