Search code examples
c#enumsasp.net-core-webapimodel-binding

Enum model binding [FromRoute] behaves differently than [FromBody] in .net core


I am getting different behaviors in the bindind model with enum and I can't get the correct value when passing information that is out of the enumeration limit.

I have a TestEnum enumeration containing Test1 = 1, Test2 = 2, Test3 = 3.

In [HttpPost] or [HttpPut] using [FromBody], my DTO object correctly receives the enumeration value, even when I pass a different value like 5 for example.

However, in a Get/Put using [FromRoute], my DTO object correctly receives enumeration when the entered values are within the enumeration limit (1, 2, or 3).

If I pass 5, the value of the enumerator becomes zero, unlike [FromBody] which can receive the value 5 normally even though it is outside of the coded Test1, Test2, and Test3.

public enum TestEnum
{
   Test1 = 1,
   Test2 = 2,
   Test3 = 3
}

It perfectly receives the values even being outside the enumeration limit.

[HttpPost]
public async Task<ActionResult<NotificationResult>> Post([FromBody]TestCommand command)

Here, in [FromRoute] and [FromBody] values are perfectly received when they are within the enumeration boundary.

When out of range, [FromRoute] gets zero and [FromBody] gets 5.

[HttpPut("{id:int}")]
public async Task<ActionResult<NotificationResult>> Put([FromRoute]TestEnum id, [FromBody]TestCommand command)

Here, in [FromRoute] values are perfectly received when they are within the enumeration boundary.

When out of range, [FromRoute] gets zero.

[HttpGet("{id:int}")]
public async Task<ActionResult<TestQueryResult>> GetById([FromRoute]TestEnum id)

I would like to receive the value even if it is outside the encoded limit in enumeration.


Solution

  • The default value of options SuppressBindingUndefinedValueToEnumType is true after .net core 2.1. So you need to change like below:

    services.AddMvc(opt=>
              opt.SuppressBindingUndefinedValueToEnumType=false)
    .SetCompatibilityVersion(CompatibilityVersion.Version_2_2); 
    

    Problem solved. Now it works.