自定义自动生成的 Swagger 定义

ims*_*san 5 swagger-ui openapi asp.net-core-webapi nswag asp.net-core-3.1

我有 swagger 设置,以便它在项目启动时使用 NSwag 基于我的 WebApi 中的控制器生成开放的 Api 规范和 Swagger Ui。我想增强 swagger Ui 以包括

  • 每个端点的摘要/描述
  • 需要参数输入的端点的示例参数输入
  • POST 调用的请求正文示例
  • 一个示例访问令牌,只能在 swagger 文档中使用,以轻松进行身份验证并能够尝试一切(有点像此示例https://petstore.swagger.io/

我是 NSwag 的新手,不确定如何将这些增强功能添加到我的代码中,例如在哪里添加它们,我需要使用什么(控制器上的注释?XML 注释?另一种方式?)我尝试过编辑“ Swagger Editor',但不知道这是如何实现的,因为它会在每次应用程序启动时重新生成。

我已阅读 NSwag 文档,但这似乎都是关于添加我已经配置的 ASP.NET Core 中间件。

编辑: 我现在在页面顶部有一个描述,并且已经能够在 XML 注释中添加带有备注标记的示例 -有没有比使用 XML 注释更优雅的方法来执行此操作?

ims*_*san 5

现在解决了这个问题,最终使用操作处理器来配置 Swagger UI/OpenApi 端点摘要、请求示例、路径参数示例值和可能的 UI 响应代码

网上没有很多文档可以用这种方式实现(我能找到的只是 XML 注释方式,所以这需要大量的试验和错误才能实现)

在这里为那些不想用 XML 注释弄乱他们的控制器的其他人发布我的解决方案。(注:该解决方案在asp.net core 3.1中可用,不确定其他版本)

  1. 将 OpenApiOperationProcessor 属性应用于控制器操作
[HttpPut("password")][OpenApiOperationProcessor(typeof(ResetPasswordOpenApiProcessor))]
public async Task<IActionResult> ResetPassword(ResetPasswordCommand request)
{
   await Mediator.Send(request);
   return Accepted();
}
Run Code Online (Sandbox Code Playgroud)
  1. 创建继承自 IOperationProcessor 的操作处理器并编写 SwaggerUI 自定义代码

下面的例子;

public class ResetPasswordOpenApiProcessor : IOperationProcessor
{
     public bool Process(OperationProcessorContext context)
     {
         context.OperationDescription.Operation.Summary = "Forgotten Password";
         context.OperationDescription.Operation.Description = "Sends a password reset email to the user with the provided email address.";

         context.OperationDescription.Operation.Parameters.Add(
                new NSwag.OpenApiParameter
             {
                 Kind = NSwag.OpenApiParameterKind.Body,
                 Description = "Forgotten Password Example",
                 Schema = new NJsonSchema.JsonSchema
                 {
                     Example = new ResetPasswordCommand()
                     {
                         Email = $"existingEmail@test.com"
                     }
                 }
             });

        context.OperationDescription.Operation.Responses.Clear();

        context.AddSuccessfulResponse(StatusCodes.Status202Accepted, "Password reset request accepted");
        context.AddBadRequestResponse();
        context.AddUnauthorizedResponse();
        context.AddInternalServerErrorResponse();

        return true;
    }
}
Run Code Online (Sandbox Code Playgroud)