我有一个ASP.NET核心2.2的WebApi,并希望上传一些额外的元数据的大文件。请求是一个多部分/表单数据。因为要上传的文件可能会非常大,所以我不想将其读取到内存中进行处理,而是直接将其流式传输到其所需的目的地。我遵循了文档为了禁用表单值模型绑定,我还调整了端点的最大请求大小。
我已经用postman测试了端点,它可以正常工作:
然而,Swagger显然没有意识到请求应该有参数。如何在不定义方法签名中的参数的情况下将这些参数添加到swagger文档中?
我的端点如下所示:
[HttpPost]
[DisableFormValueModelBinding]
[DisableRequestSizeLimit]
public async Task Upload() // "department" and "file" needed in the multipart/form-data
{
// var path = await uploader.UploadAsync(Request);
// return Ok(path);
}
通常,我会像下面这样绑定参数:
public async Task Upload([FromForm] string department, [FromForm] IFormFile file)
这在Swagger中可以正常工作,但如上所述,我不想绑定参数。
发布于 2021-02-23 01:15:29
对于Swashbuckle.AspNetCore版本5和更高版本,有些东西已经改变了。
要像Alexander在他的答案中那样提供参数,代码将类似于以下内容:
operation.Parameters.Add(new OpenApiParameter()
{
Name = "department",
Schema = new OpenApiSchema { Type = "string", Format = "string" },
Required = true,
});
operation.Parameters.Add(new OpenApiParameter()
{
Name = "file",
Schema = new OpenApiSchema { Type = "string", Format = "binary" },
Required = true,
});
但是,由于某些原因(我没有进一步研究),我无法使用这种方法在Swagger UI中执行调用。
最后,下面的示例给出了我想要的结果:
public class AddUnboundParametersOperationFilter : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
var descriptor = context.ApiDescription.ActionDescriptor as ControllerActionDescriptor;
if (descriptor != null && descriptor.ControllerTypeInfo == typeof(RemoteUpdateController) && descriptor.ActionName == nameof(RemoteUpdateController.Upload))
{
var openApiMediaType = new OpenApiMediaType
{
Schema = new OpenApiSchema
{
Type = "object",
Required = new HashSet { "department", "file" }, // make the parameter(s) required if needed
Properties = new Dictionary
{
{ "department" , new OpenApiSchema() { Type = "string", Format = "string" } },
{ "file" , new OpenApiSchema() { Type = "string", Format = "binary" } },
}
}
};
operation.RequestBody = new OpenApiRequestBody
{
Content = new Dictionary
{
{ "multipart/form-data", openApiMediaType }
}
};
}
}
}
发布于 2021-02-20 09:42:49
您可以使用IOperationFilter为了这个。添加以下类,调整控制器和动作名称
public class AddUnboundParametersOperationFilter : IOperationFilter
{
public void Apply(Operation operation, OperationFilterContext context)
{
if (operation.Parameters == null)
operation.Parameters = new List();
var descriptor = context.ApiDescription.ActionDescriptor as ControllerActionDescriptor;
if (descriptor != null && descriptor.ControllerTypeInfo == typeof(TestController) && descriptor.ActionName == nameof(TestController.Upload))
{
operation.Parameters.Add(new NonBodyParameter()
{
Name = "department",
Type = "string",
Required = true,
In = "formData",
});
operation.Parameters.Add(new NonBodyParameter()
{
Type = "file",
In = "formData",
Name = "file",
Required = true
});
}
}
}
在Startup.cs
services.AddSwaggerGen(c =>
{
c.OperationFilter();
//...
});
https://stackoverflow.com/questions/66256229
复制相似问题