使swashbuckle中的参数可选(不是必需的)

时间:2017-10-01 09:11:31

标签: asp.net-core swagger

我想在我的控制器中将param作为可选项,但是swagger会根据需要显示它。

我的控制器看起来像:

[HttpGet("{name}")]
[SwaggerResponse((int)HttpStatusCode.OK)]
[SwaggerResponse((int)HttpStatusCode.BadRequest)]
public async Task<IActionResult> GetPolicy(string name)
 {
     if (string.IsNullOrEmpty(name))
     {
         return BadRequest("Name is empty");
     }
     try
     {
         CRUDPolicyResponse crudPolicyResponse = await _managementOperations.CRUDPolicy(CRUDType.Read, name, null);
         if (!crudPolicyResponse.OperationSucceeded)
         {     
            return StatusCode((int)HttpStatusCode.BadRequest, crudPolicyResponse.Message);
         }
         if (crudPolicyResponse.FileMetadataPolicy == null)
         {
             return NotFound($"Policy name doesn't exists NAME: {name}");
         }
         return Ok(crudPolicyResponse.FileMetadataPolicy);
     }
     catch (Exception ex)
     {
        _log.Error("Error while trying to save file meta data policy", ex);
            return StatusCode((int)HttpStatusCode.InternalServerError, ex);
     }
 }

我尝试更改为默认值,如下所示:string name = null但不能正常工作/ swashbuckle looks like this

因此名称字符串是必需的,我不能将名称变为空。

我尝试用这个解决方案来解决我的问题 make int as nullable

3 个答案:

答案 0 :(得分:2)

将默认值添加到控制器参数

[HttpGet("{name}")]
[SwaggerResponse((int)HttpStatusCode.OK)]
[SwaggerResponse((int)HttpStatusCode.BadRequest)]
public async Task<IActionResult> GetPolicy(string name = "")
 {
...
}

答案 1 :(得分:1)

使用 FromQuery 更改您的参数,如下所示:

public async Task<IActionResult> GetPolicy([FromQuery] string name)

答案 2 :(得分:0)

我自己最近遇到了这个问题,并通过添加第二个端点解决了该问题:

您的原始签名:

[HttpGet("{name}")]
[SwaggerResponse((int)HttpStatusCode.OK)]
[SwaggerResponse((int)HttpStatusCode.BadRequest)]
public async Task<IActionResult> GetPolicy(string name)

和新的:

[HttpGet("")]
[SwaggerResponse((int)HttpStatusCode.OK)]
[SwaggerResponse((int)HttpStatusCode.BadRequest)]
public async Task<IActionResult> GetPolicy()

自然地,这导致了方法主体的重构,两个端点变成了箭头方法:

protected async Task<CRUDPolicyResponse> GetPolicy(string name = null) {
...
}

[HttpGet("{name}")]
[SwaggerResponse((int)HttpStatusCode.OK)]
[SwaggerResponse((int)HttpStatusCode.BadRequest)]
public async Task<IActionResult> GetPolicyByName(string name) =>  OK(await GetPolicy(name));

[HttpGet("")]
[SwaggerResponse((int)HttpStatusCode.OK)]
[SwaggerResponse((int)HttpStatusCode.BadRequest)]
public async Task<IActionResult> GetPolicyAnyPolicy() => OK(await GetPolicy());