如何告诉 Swashbuckle 5 在 dotnetcore 3.0 中需要正文内容?

ajt*_*tum 2 swagger swagger-ui .net-core swashbuckle asp.net-core-3.0

我正在尝试实现 Swashbuckle 5,并且我有几种方法可以像这样读取请求正文:

var requestBody = await Request.GetRawBodyStringAsync();
Run Code Online (Sandbox Code Playgroud)

我如何告诉 Swashbuckle/Swagger 将其作为参数读取,以便人们可以测试我的 API?我看到这里有人了一个非常相似的问题,但那是针对二进制内容和早期版本的 Swashbuckle。

任何帮助将不胜感激!

Ale*_*esD 9

正如您在 Swashbuckle 5 中已经发现的那样,它有所不同,因为它转而使用Microsoft OpenApi.NET SDK。这就是对象模型不同的原因。否则它仍然以与您链接的帖子中的示例相同的方式工作。我已将案例转换为您想要发送原​​始文本字符串的场景。

创建一个自定义属性来标记读取原始字符串的方法。例如:

public class RawTextRequestAttribute : Attribute
{
   public RawTextRequestAttribute()
   {
      MediaType = "text/plain";
   }

   public string MediaType { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

要修改 Swagger 定义,您需要一个Swashbuckle 操作过滤器来检查此属性,如果找到,则将请求正文自定义为纯字符串。这是一个示例实现:

public class RawTextRequestOperationFilter : IOperationFilter
{
   public void Apply(OpenApiOperation operation, OperationFilterContext context)
   {
      RawTextRequestAttribute rawTextRequestAttribute = context.MethodInfo.GetCustomAttributes(true)
         .SingleOrDefault((attribute) => attribute is RawTextRequestAttribute) as RawTextRequestAttribute;
      if (rawTextRequestAttribute != null)
      {
         operation.RequestBody = new OpenApiRequestBody();
         operation.RequestBody.Content.Add(rawTextRequestAttribute.MediaType, new OpenApiMediaType() 
         {
            Schema = new OpenApiSchema()
            {
               Type = "string"
            }
         });
      }
   }
}
Run Code Online (Sandbox Code Playgroud)

对于要使用的过滤器,您需要在配置 Swagger 时在启动时注册它。

public void ConfigureServices(IServiceCollection services)
{
   services.AddControllers();
   services.AddSwaggerGen(c =>
   {
      c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
      c.OperationFilter<RawTextRequestOperationFilter>();
   });
}
Run Code Online (Sandbox Code Playgroud)

然后将该属性添加到读取原始请求的方法中。例如:

[HttpPost]
[RawTextRequest]
public async Task Post()
{
   var requestBody = await Request.GetRawBodyStringAsync();
   _logger.LogDebug(requestBody);
}
Run Code Online (Sandbox Code Playgroud)

结果是您在 Swagger UI 中获得了请求正文的文本输​​入框。

招摇的用户界面

  • 您可以使用“Example”属性来更改它。这是显示的示例值关于默认值是错误的。例如,要具有空字符串值,请设置 `Example = new OpenApiString("")` (2认同)