0

I'm facing a weird problem when using a list of Enum in an ASP.NET Core 7 Web API .

The client and server side each have the same copy of an Enum class. The formated value of the Uri created by the client is

api/ApiName/?Id=57&ListEnum=EnumVal1,EnumVal2,EnumVal3

On the Web API side, the controller is defined as:

 public async Task<ActionResult> ApiName([FromQuery] int Id, [FromQuery] List<EnumName> ListEnum) 

When called however, the Web API is not getting all the values. In fact, there is only one item in the list and it's not even the correct value. Like EnumVal4.

I have the JsonStringEnumConverter added in the services :

builder.Services.AddControllers()
.AddJsonOptions(opt => { opt.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); }); 

Is there a way to keep the enum and have things working properly?

1
  • You might be facing this issue due to URL formatting, Enum definitions, or ASP.NET Core's handling of query parameters. To resolve this, try explicitly naming the query parameter with [FromQuery(Name = "ListEnum")]. You could also use custom model binding for better deserialization control. Verify that both client and server have identical Enum definitions. Use tools like Postman to test the API and rule out client-specific issues. Make sure JsonStringEnumConverter is set up correctly. Commented Aug 26, 2023 at 15:23

1 Answer 1

0

The EnumName class is a object, and the correct query url should be like below.

api/ApiName/?Id=1&ListEnum[0].ValueName=EnumVal1&ListEnum[1].ValueName=EnumVal2&ListEnum[2].ValueName=EnumVal3&ListEnum[3].ValueName=EnumVal4

My test code and result

EnumName.cs

public class EnumName { 
    public string? ValueName { get; set; }
}

Test Controller

[ApiController]
[Route("[controller]")]
public class TestController : ControllerBase
{
    public async Task<IActionResult> ApiName([FromQuery] int Id, [FromQuery] List<EnumName> ListEnum) {
        return Ok("Id = "+ Id + " and ListEnum Count = "+ ListEnum.Count().ToString());
    }
}

Test Result

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

You're right. I was using the QueryStringHelper from the framework so I hadn't the choice of the format but writing my own helper I've been able to get it working like your solution. It's strange though that the .net is not consistent in their "standards".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.