【问题标题】:Swashbuckle.AspNetCore required query string parameterSwashbuckle.AspNetCore 所需的查询字符串参数
【发布时间】:2019-05-17 12:39:19
【问题描述】:

我有一个带有 Swashbuckle.AspNetCore 包的 ASP.NET Core v2.1 项目。 我的代码是:

    /// <summary>
    /// Set new android token for the current driver
    /// </summary>
    /// <remarks>
    /// Sample request:
    ///
    ///     PUT /SetToken?token=new_token
    ///
    /// </remarks>
    /// <param name="token">can't be null or empty</param>
    /// <returns></returns>
    /// <response code="204">If executed successfully</response>
    /// <response code="400">if token is null or empty</response>  
    /// <response code="404">if user is not a driver; if driver is not found (removed etc); if user does not have a profile</response>  
    [ProducesResponseType(204)]
    [ProducesResponseType(400)]
    [ProducesResponseType(404)]
    [HttpPut]
    [Route("SetToken")]
    [UserIsNotDriverException]
    [NullReferenceException]
    [DriverWithoutProfileException]
    public async Task<IActionResult> SetToken([FromQuery]string token)
    {

我想根据需要标记查询参数。我该怎么做?注意,我在查询字符串中传递参数,而不是在正文等中

【问题讨论】:

  • 查询字符串本质上是可选的。这只是 HTTP 规范。如果您需要某些东西,它应该是路由的一部分(即实际的 URL 路径)。也就是说,像 POST 和 PUT 这样的方法有一个请求主体,而数据的正确位置是在主体中。您几乎不应该使用带有 PUT 之类的查询字符串。

标签: asp.net-core swagger swashbuckle


【解决方案1】:

您可以将BindRequired 属性添加到您的参数中。

public async Task<IActionResult> SetToken([FromQuery, BindRequired]string token)

【讨论】:

  • 这至少需要 .Net Core 2.1 才能使“ModelState.IsValid”正常运行,请参阅:andrewlock.net/…
【解决方案2】:

你可以这样做。

public async Task<IActionResult> SetToken([FromQuery, SwaggerParameter("Token Description", Required = True)]string token)

使用这个库 Swashbuckle.AspNetCore.Annotations 会有所帮助。

【讨论】:

    猜你喜欢
    • 2020-09-01
    • 1970-01-01
    • 2015-04-19
    • 1970-01-01
    • 1970-01-01
    • 2016-03-27
    • 1970-01-01
    • 2012-02-07
    • 1970-01-01
    相关资源
    最近更新 更多