I’m trying to create a GET-Route which takes 4 optional Parameter. There are no required Parameter.
My Route looking like that
[Produces("application/json")]
[HttpGet("SearchWhatever", Name = "GetWhatever")]
public IEnumerable<TmpObject> SearchWhatever(long? eid= null, long? pid = null, string name= null, string firstname= null)
{
//do Smth
}
Basically the “eid” and the “pid” are working as intended, they’re completely optional. However the strings are not working as “optional”.
If I’m calling the API like “../SearchWhatever?eid=6610232513694” I’ll receive the following error:
{
errors: {
name: [
"The name field is required."
],
firstname: [
"The firstname field is required."
]
},
type: "https://tools.ietf.org/html/rfc7231#section-6.5.1",
title: "One or more validation errors occurred.",
status: 400,
traceId: "00-e4eb5dc9bb266e44abda734d6a411e44-5f5a40de7fc10540-00"
}
How do I achieve my goal? Is it even possible? I thought giving a string a default value like null makes the parameter optional already.
Thanks in advance
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Here is a demo worked,firstly
add this to your controller:
#nullable enable
action(use string? name,string? firstname,because you use nullable enable,so the string type can be null):
[HttpGet]
[Route("SearchWhatever")]
public IEnumerable<String> SearchWhatever(long? eid, long? pid,string? name,string? firstname)
{
return new List<String> { "success" };
//do Smth
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0
