gpt4 book ai didi

asp.net-web-api - 我怎样才能告诉Swashbuckle人体必需的成分?

转载 作者:行者123 更新时间:2023-12-04 10:35:19 26 4
gpt4 key购买 nike

我有一个WebAPI Controller ,它接受二进制包并将它们存储在某个地方。由于这些包可能会变得很大,因此我不想通过添加字节数组参数将它们加载到内存中,而是希望将其传递给流。

我找到了一种方法in this answer:

[HttpPost]
[Route("Store/{projectId}")]
public async Task Store(string projectId)
{
using (var stream = await this.Request.Content.ReadAsStreamAsync())
{
await this.packageManager.StorePackageAsync(projectId, stream);
}
}

这可行,我可以使用Postman将文件发送到 Controller 。但是,我现在想用Swashbuckle生成详尽的文档,当然,这里没有提到所需的正文内容。

有没有办法获取请求内容的流,以便Swashbuckle知道呢?还是有一个我可以用来告知所需内容的属性?

最佳答案

要实现这一点,您必须做几件事。

首先,您必须告诉Swagger主体中有一个包含二进制数据的参数。接下来,您必须告诉Swagger端点消耗二进制数据(例如application/octet-stream)。

Swashbuckle不支持此功能。但是您可以创建自定义过滤器来扩展Swashbuckle的功能。我通常要做的是创建一个自定义属性来装饰方法,然后创建一个自定义过滤器以对该属性进行操作。

在您的情况下,这可以解决问题:

自定义属性

public class BinaryPayloadAttribute : Attribute
{
public BinaryPayloadAttribute()
{
ParameterName = "payload";
Required = true;
MediaType = "application/octet-stream";
Format = "binary";
}

public string Format { get; set; }

public string MediaType { get; set; }

public bool Required { get; set; }

public string ParameterName { get; set; }
}

自定义过滤器
public class BinaryPayloadFilter : IOperationFilter
{
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
var attribute = apiDescription.GetControllerAndActionAttributes<BinaryPayloadAttribute>().FirstOrDefault();
if (attribute == null)
{
return;
}

operation.consumes.Clear();
operation.consumes.Add(attribute.MediaType);

operation.parameters.Add(new Parameter
{
name = attribute.ParameterName,
@in = "body",
required = attribute.Required,
type = "string",
format = attribute.Format
});
}
}

将过滤器添加到Swashbuckle配置
GlobalConfiguration.Configuration 
.EnableSwagger(c =>
{
// other configuration setting removed for brevity
c.OperationFilter<BinaryPayloadFilter>();
});

将属性应用于方法
[HttpPost]
[BinaryPayload]
[Route("Store/{projectId}")]
public async Task Store(string projectId)
{
...
}

在Swagger UI中,您将得到:

Swagger UI

关于asp.net-web-api - 我怎样才能告诉Swashbuckle人体必需的成分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41141137/

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