在使用Swashbuckle上传文件的时候,在接口文档中希望看到上传控件,但是C#中,没有FromBodyAttribute这个特性,所以需要在运行时,修改参数的swagger属性。
首先看下,最终效果:
![](https://images2015.cnblogs.com/blog/533569/201704/533569-20170410110853657-2094491567.png)
下面介绍实现。
实现原理,通过swagger提供的filter,找到action中带有SwaggerFileUpload特性的参数,然后给swagger operaion.parameters添加一个自定义的参数,即文件类型参数即可。
(1)定义SwaggerFileUploadAttribute。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
[AttributeUsage(AttributeTargets.Parameter)] public class SwaggerFileUploadAttribute : Attribute { public bool Required { get; private set; } public SwaggerFileUploadAttribute(bool Required = true) { this.Required = Required; } }
(2)添加Filter。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
/// <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" }); } } } }
(3)给Swagger设置Filter。
![](https://images2015.cnblogs.com/blog/533569/201704/533569-20170410112948985-1813011100.png)
(4)Action中的参数设置特性,测试。
Public void TestSwaggerUploadFile([SwaggerFileUpload] file){ }
以上四部就可以实现文章开头的效果了。