❔ C# WebAPI - how to make a field 'optional' ?
I'm creating some WebAPI, I'm starting from a get, for the retrieval of users from a DB.
I'm using .NET 7.0 and EntityFramework.
The form that make the search request can take in input those fields:
Database ID
User ID
FromDate
ToDate
Username
All fields must be optional, obviously at least 1 should be sent.
I wrote some code:
As I understood, in that way EF understand how should it works, and the statement should works without bugs.
I think I'll only have to add a check at the beginning, for make sure that at least 1 field is sent.
Anyway when I test the API and I put only 1 field, for example dbId
I get Error 400
as response, The username field is required
I suppose that's why I never declared anywhere when the parameter is optional, and when not, since I just defined the code that have to be executed after a correct request is sent.
Browsing on the web I found some guides that suggest to add [Required]
tag on mandatory fields, inside the model.cs making the rest being optional, but this seems not working.
Other guides suggest to set all parameters to null
by default, or at least setting the FrontEnd to work in this way.3 Replies
make
username
be string?
instead of string
Oh, damn it was easier than expected.
I left just it without the
?
for avoid blank request, but I didn't mind good.
Regarding the inside code I think it should works good, only one thing, for some reason, yeah obvious reason, if all fields are sent in blank, the output will be all elements.
Which could be a proper way to make sure that at least one field is sent?
Could an if
with multiple condition works? that maybe return some response code.
Actually I did in in this way and it seems working, idk if is there a more elegant way to write the code.
Now I'm just wondering if I could go on or if I should add some other code in order to get it more efficient.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.