gpt4 book ai didi

.net-core - 我如何告诉 Swashbuckle 5 在 dotnetcore 3.0 中需要主体内容?

转载 作者:行者123 更新时间:2023-12-05 08:39:44 25 4
gpt4 key购买 nike

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

var requestBody = await Request.GetRawBodyStringAsync();

如何让 Swashbuckle/Swagger 将其作为参数读取,以便人们可以测试我的 API?我看到一个很similar question being asked here但那是针对二进制内容和早期版本的 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 中获得请求正文的文本输​​入框。

Swagger UI

关于.net-core - 我如何告诉 Swashbuckle 5 在 dotnetcore 3.0 中需要主体内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59183269/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com