简体   繁体   中英

ASP.NET Core modelbinding pickups up default enum value in case when the enum item is not available

I have an ASP.NET Core 3.1 Web API project. There is an enum with the following details:

public enum TestPageType
{
    Item1,
    Item2,
    Item3,
    Item4
}

[HttpGet("{type}/{mode}")]
[ProducesResponseType(400)]
[ProducesResponseType(500)]
public IEnumerable<ControlInfo> GetControlData(TestPageType type, string mode)
{
    switch (type)
    {
        case TestPageType.Item1:
        case TestPageType.Item2:
        case TestPageType.Item3:
        case TestPageType.Item4:
        default:
            return _testService.GetData(GetControlType(type), 0, readonlyMode);
    }
}

From the client application, Item5 is sent as input to the API endpoint:

https://localhost:8080/api/test/GetControlData/item5/edit

In this on debugging I see that first item from the TestPageType enum: Item1 is picked.

Can anyone help me to resolve this issue?

By default, the associated constant values of enum members are of type int; they start with zero and increase by one following the definition text order. And the default value of an enumeration type E is the value produced by expression (E)0, even if zero doesn't have the corresponding enum member. More detail information, see Enumeration types (C# reference) .

In your code, since the TestPageType doesn't has the Items5 item, so it will use the default value (Item1).

To receive the not exist item: "Item5", you can try to change the parameter type from TestPagetType to string type. Then check whether the value is the enum value.

Code like this:

    [HttpGet("{type}/{mode}")]
    [ProducesResponseType(400)]
    [ProducesResponseType(500)]
    public IActionResult GetControlData(string type, string mode)
    { 
        var selectitem = "";
        switch (type)
        {
            case "Item1" :
                selectitem =  TestPageType.Item1.ToString();
                break;
            case "Item2":
                selectitem = TestPageType.Item2.ToString();
                break;
            case "Item3":
                selectitem = TestPageType.Item3.ToString();
                break;
            case "Item4":
                selectitem = TestPageType.Item4.ToString();
                break;
            default:
                selectitem = "no exist";
                break;
        }

        return Ok(selectitem);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM