C# 将可选URL参数捕获为局部变量

C# 将可选URL参数捕获为局部变量,c#,api,C#,Api,我正在尝试创建一个双重用途的API端点。其思想是,如果用户传入可选参数checkExistence,则响应将为true或false,这取决于基础数据库表中是否存在formulaId+bucket+scenarioName组合。另一方面,如果未传入checkExistence参数,则响应将为404未找到或数据(如果组合不存在)或数据(如果组合确实存在)。以下是迄今为止的代码: [HttpGet("{scenarioName}/{bucket}/{formulaId}/{checkExistence

我正在尝试创建一个双重用途的API端点。其思想是,如果用户传入可选参数
checkExistence
,则响应将为true或false,这取决于基础数据库表中是否存在formulaId+bucket+scenarioName组合。另一方面,如果未传入
checkExistence
参数,则响应将为404未找到或数据(如果组合不存在)或数据(如果组合确实存在)。以下是迄今为止的代码:

[HttpGet("{scenarioName}/{bucket}/{formulaId}/{checkExistence?}")]
public virtual async Task<IActionResult> GetAsync(string scenarioName, DateTime bucket, string formulaId)
{
    var dto = await DataService.GetAsync(new object[] { formulaId, bucket, scenarioName });

    string? checkExistence = "";

    if (string.IsNullOrEmpty(checkExistence))
    {
        if (dto == null)
        {
            return NotFound();
        }
        return Ok(dto);
    }
    else
    {
        return (dto == null) ? Ok(false) : Ok(true);
    }
}
[HttpGet(“{scenarioName}/{bucket}/{formulaId}/{checkExistence?}”)]
公共虚拟异步任务GetAsync(字符串scenarioName、DateTime bucket、字符串formulaId)
{
var dto=await DataService.GetAsync(新对象[]{formulaId,bucket,scenarioName});
字符串?checkExistence=“”;
if(string.IsNullOrEmpty(checkExistence))
{
if(dto==null)
{
返回NotFound();
}
返回Ok(dto);
}
其他的
{
返回(dto==null)?正常(false):正常(true);
}
}

当点击端点时,它的行为就好像
checkExistence
始终为空,即使在该参数的URL中传递了一个值。我怀疑这是因为URL中的
{checkExistence?}
没有被赋值给局部变量
checkExistence
…但我不知道如何进行赋值来检验这个理论。有没有办法完成这个任务?API这样做还有其他原因吗?

可选路由参数需要作为可选参数包含在方法签名中。然后可以删除方法中声明的变量:

[HttpGet("{scenarioName}/{bucket}/{formulaId}/{checkExistence?}")]
public virtual async Task<IActionResult> GetAsync(string scenarioName, DateTime bucket, string formulaId, string checkExistence = null)
{
    var dto = await DataService.GetAsync(new object[] { formulaId, bucket, scenarioName });

    if (string.IsNullOrEmpty(checkExistence))
    ...
}
[HttpGet(“{scenarioName}/{bucket}/{formulaId}/{checkExistence?}”)]
公共虚拟异步任务GetAsync(string scenarioName、DateTime bucket、string formulaId、string checkExistence=null)
{
var dto=await DataService.GetAsync(新对象[]{formulaId,bucket,scenarioName});
if(string.IsNullOrEmpty(checkExistence))
...
}
有关更多详细信息,请参阅