Asp.net 仅带有可选参数的核心 WebAPI 路由不起作用

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

我正在尝试创建一个带有 4 个可选参数的 GET 路由。没有必填参数。

我的路线看起来像那样

    [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
    }

基本上“eid”和“pid”按预期工作,它们是完全可选的。但是,字符串不能作为“可选”使用。

如果我像“../SearchWhatever?eid=6610232513694”这样调用 API,我将收到以下错误:

{
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"
}

我如何实现我的目标?有可能吗?我想给一个字符串一个默认值,比如 null 使得参数已经可选。

提前致谢

这是一个演示,首先 将此添加到您的控制器:

#nullable enable

action(使用string? name,string? firstname,因为你使用nullable enable,所以字符串类型可以为null):

[HttpGet]
        [Route("SearchWhatever")]
        public IEnumerable<String> SearchWhatever(long? eid, long? pid,string? name,string? firstname)
        {
            return new List<String> { "success" };
            //do Smth
        }

结果: