我正在尝试实现Swashbuckle 5,我有几种读取请求主体的方法,如下所示:
var requestBody = await Request.GetRawBodyStringAsync();
我如何告诉Swashbuckle / Swagger将其作为参数读取,以便人们可以测试我的API?我看到了一个非常similar question being asked here,但这是针对Binary内容和Swashbuckle的早期版本的。
任何帮助将不胜感激!
正如您已经在Swashbuckle 5中发现的那样,它有所不同,因为它切换为使用Microsoft OpenApi.NET SDK。这就是对象模型不同的原因。否则,它仍然与您链接的帖子中的示例相同。我已将案例翻译为您要发送原始文本字符串的情况。
创建自定义属性以标记读取原始字符串的方法。例如:
public class RawTextRequestAttribute : Attribute
{
public RawTextRequestAttribute()
{
MediaType = "text/plain";
}
public string MediaType { get; set; }
}
要修改Swagger定义,您需要Swashbuckle operation filter,它将检查此属性,如果找到,则将请求正文自定义为纯字符串。这是执行此操作的示例实现:
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"
}
});
}
}
}
要使用的过滤器,在配置Swagger时需要在启动时注册它。
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
c.OperationFilter<RawTextRequestOperationFilter>();
});
}
然后将属性添加到读取原始请求的方法中。例如:
[HttpPost]
[RawTextRequest]
public async Task Post()
{
var requestBody = await Request.GetRawBodyStringAsync();
_logger.LogDebug(requestBody);
}
结果是您在Swagger UI中获得了请求正文的文本输入框。