Amira
Amira
CC#
Created by Amira on 7/20/2023 in #help
❔ How to convert query string to an Enum in a custom way
I have the following code: .
[HttpGet]
public async Task<IActionResult> GetCarsAsync([FromQuery] GetCarsApiQuery query)
{

}

public class GetCarsApiQuery
{
public string? VehicleId { get; set; }


public VehicleType? VehicleType { get; set; } //Cannot change its type to string
}

public enum VehicleType {
Car,
Bike,
Undefined
}
[HttpGet]
public async Task<IActionResult> GetCarsAsync([FromQuery] GetCarsApiQuery query)
{

}

public class GetCarsApiQuery
{
public string? VehicleId { get; set; }


public VehicleType? VehicleType { get; set; } //Cannot change its type to string
}

public enum VehicleType {
Car,
Bike,
Undefined
}
By default, If I send a GET request with a VehicleType = Foo, the framework will return a bad request. I want to change this behavior so that when it tries to convert the query string to VehicleType, it either succeed or returns VehicleType.Undefined In other words, I am looking for something like a custom JsonConverter but that works on query strings rather than json body any ideas ?
70 replies