Abp中SwaggerUI的接口文档添加上传文件参数类型


在使用Swashbuckle上传文件的时候,在接口文档中希望看到上传控件,但是C#中,没有FromBodyAttribute这个特性,所以需要在运行时,修改参数的swagger属性。
 
首先看下,最终效果:
 
 
下面介绍实现。
 
实现原理,通过swagger提供的filter,找到action中带有SwaggerFileUpload特性的参数,然后给swagger operaion.parameters添加一个自定义的参数,即文件类型参数即可。
 
(1) 定义SwaggerFileUploadAttribute。
[AttributeUsage(AttributeTargets.Parameter)]
public class SwaggerFileUploadAttribute : Attribute
{
public bool Required { get; private set; }
 
public SwaggerFileUploadAttribute(bool Required = true)
{
this.Required = Required;
}
}
View Code

 

(2) 添加Filter。
/// <summary>
/// swagger file upload parameter filter
/// </summary>
public class SwaggerFileUploadFilter : IOperationFilter
{
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
var parameters = apiDescription.ActionDescriptor.GetParameters();
foreach (HttpParameterDescriptor parameterDesc in parameters)
{
var fileUploadAttr = parameterDesc.GetCustomAttributes<SwaggerFileUploadAttribute>().FirstOrDefault();
if (fileUploadAttr != null)
{
operation.consumes.Add("multipart/form-data");
 
operation.parameters.Add(new Parameter
{
name = parameterDesc.ParameterName + "_file",
@in = "formData",
description = "file to upload",
required = fileUploadAttr.Required,
type = "file"
});
}
}
}
}
View Code

 

(3) 给Swagger设置Filter。

 

(4) Action中的参数设置特性,测试。
Public void TestSwaggerUploadFile([SwaggerFileUpload] file){ }
 
以上四部就可以实现文章开头的效果了。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM