❔ Prevent accepting numeric values as enum
Hello, I have an API that exposes an enum field Vehicle (Car, Bike, Truck) in the POST. The problem is that when I POST a request with a body
{"vehicle" :"1" }
, it gets accepted and gets automatically converted to Vehicle.Bike.. But something like {"vehicle" :"bar" }
results in a bad request, which is what I need !
Any idea on how to stop parsing integer like enum values?17 Replies
You would require a custom mapping for that
As enums are, at their core, integers
So by default they're gonna end up as numbers
Depending on how you are mapping your model, newtownoft Vs STJ, the requirements for this will probably differ
I am unsure how you would explicitly make it a bad request to pass it as a number but you can probably bake it into the custom mapping somehow
What do you mean by a custom mapping ?
By default when you're using a model it will do it's best based on the reflection data to build a JSON object
If you want behaviour that is different you have to specify it yourself
Okay I see !
Do you have some code examples on how to do this things ?
^
But even if I knew this it's been too long for me to remember exactly
Your best bet is the documentation for whatever it is you're using for this
I've found something like this https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/converters-how-to?pivots=dotnet-7-0
How to write custom converters for JSON serialization - .NET
Learn how to create custom converters for the JSON serialization classes that are provided in the System.Text.Json namespace.
Is that what you mean ?
ovveriding the
Read
and Wrtie
function of the jsonConverter of the enumIf you are using STJ
That will probably do it
Yu I am using STJ
Well all I can say is give it a whirl and see what explodes 🙂
Yup, but still thinking about how to say "is not an integer value" 😆
Oh maybe there is some
int.TryParse
by defaultI'm sure you'll figure it iut
Out*
MSDocs are some of the best around after all
yup yup, thanks dude 🙏
STJ also has a string enum converter that accepts a bool setting whether integers are valid.
yeah but when putting it to false, it will not accept 1,2,3 etc. but still accepts "1","2","3" etc.
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.