user9491184
user9491184

Reputation:

Asp.net core WebAPI route with optional parameter only not working

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

Upvotes: 1

Views: 2462

Answers (1)

Yiyi You
Yiyi You

Reputation: 18159

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
        }

result: enter image description here

Upvotes: 4

Related Questions