C
C#3d ago
sl8er

Binding case-insensitive query parameter to string enum in .NET 9 Minimal API

I have an order query parameter that I'd like to bind to an Order enum in a minimal API endpoint ([FromQuery] Order order = Order.Desc).
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum Order
{
[JsonStringEnumMemberName("asc")] Asc,

[JsonStringEnumMemberName("desc")] Desc
}
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum Order
{
[JsonStringEnumMemberName("asc")] Asc,

[JsonStringEnumMemberName("desc")] Desc
}
I'd like to accept all values like "ASC", "asc", "Asc", but currently only "Asc" and "Desc" work. I get a bad request with Microsoft.AspNetCore.Http.BadHttpRequestException: Failed to bind parameter "Order order" from "desc".
1 Reply
Thalnos
Thalnos3d ago
one way to do this is to create a custom modelbinder https://learn.microsoft.com/en-us/aspnet/core/mvc/advanced/custom-model-binding?view=aspnetcore-9.0 I dont think you can make the default modelbinder case insensitive mhm actually screw that, I'm reading right now that the default model binding in asp.net core is case insensitive by default o.O oh I think I understand why its not working. Microsoft.AspNetCore.Http.Json.JsonOption holds PropertyNameCaseInsensitive = true but the fields in an enum aren't properties. You can only make property binding case insensitive it seems. Consider changing your enum to a class,record or struct to make it case insensitive

Did you find this page helpful?