【问题标题】:How to remove unnecessary fields from autogenerated Swagger doc endpoint?如何从自动生成的 Swagger 文档端点中删除不必要的字段?
【发布时间】:2019-09-09 17:44:30
【问题描述】:

目前我有以下用户模型

public class User {
    [Key]
    public int Id { get; set; }

    [Required]
    public string Name { get; set; }

    [Required]
    public string Email { get; set; }

    [Required]
    public string Password { get; set; }

}

以及以下接收电子邮件和密码的 Auth Endpoint:

[AllowAnonymous]
[HttpPost("[action]")]
public IActionResult Authenticate([FromBody] User operatorParam) {
    var user = _userService.Authenticate(operatorParam.Email, operatorParam.Password);

    if (user == null) {
        return BadRequest(new {message = "Email or password is incorrect"});
    }

    return Ok(user);
}

Swagger 自动文档正在生成以下内容:

有什么方法可以从示例中删除 ID、名称和令牌?因为在这个特定端点中只需要电子邮件和密码。

【问题讨论】:

  • 你使用 Swashbuckle 还是 Swagger-Net?
  • @Helen Swashbuckle
  • 我会用 DocumentFilter 来做,如果你需要一个模型,你可能会得到相同的模型,一个 DocFilter 可以满足你的需要。
  • @HelderSepulveda 阅读 DocumentFilter 我只发现完全隐藏了一个动作或一个变量。但不仅仅是一个端点。你能给我举个例子吗?

标签: c# .net swagger swashbuckle


【解决方案1】:

为请求正文创建另一个模型

    public class UserRequest {
        public string Name { get; set; } //you can also remove this
        public string Email { get; set; }
        public string Password { get; set; }

    }

    [AllowAnonymous]
    [HttpPost("[action]")]
    public IActionResult Authenticate([FromBody] UserRequest operatorParam) {
        var user = _userService.Authenticate(operatorParam.Email, operatorParam.Password);

        if (user == null) {
            return BadRequest(new {message = "Email or password is incorrect"});
        }

        return Ok(user);
    }

有一个例子你可以关注这个Example

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-25
    • 1970-01-01
    • 2018-08-27
    • 2018-07-06
    • 1970-01-01
    • 1970-01-01
    • 2018-07-07
    • 2018-12-20
    相关资源
    最近更新 更多