我正在尝试设置 swagger 来测试具有 IFormFile 属性的模型。
例如我有下一个 api 方法
[HttpPost]
public ApiResult<UserModel> SaveTestFileData([FromForm]TestPostFileArgs args)
{
var result = new UserModel() { Id = 1, Name = $"SaveTestFileData {args.UserId} company: {args.CompanyId}, file length: {args.CompanyFile.Length}" };
return ApiResult.Success(result);
}
还有我的参数模型
public class TestPostFileArgs
{
public int UserId { get; set; }
public int? CompanyId { get; set; }
public IFormFile CompanyFile { get; set; }
}
By default swagger generate help page which does not allow to test it
To solve this problem I wrote next OperationFilter
public class FormFileOperationFilter: IOperationFilter
{
public void Apply(Operation operation, OperationFilterContext context)
{
if (operation.Parameters == null)
return;
var fileParamNames = context.ApiDescription.ActionDescriptor.Parameters
.SelectMany(x => x.ParameterType.GetProperties())
.Where(x => x.PropertyType.IsAssignableFrom(typeof (IFormFile)))
.Select(x => x.Name)
.ToList();
if (!fileParamNames.Any())
return;
var paramsToRemove = new List<IParameter>();
foreach (var param in operation.Parameters)
{
paramsToRemove.AddRange(from fileParamName in fileParamNames where param.Name.StartsWith(fileParamName + ".") select param);
}
paramsToRemove.ForEach(x => operation.Parameters.Remove(x));
foreach (var paramName in fileParamNames)
{
var fileParam = new NonBodyParameter
{
Type = "file",
Name = paramName,
In = "formData"
};
operation.Parameters.Add(fileParam);
}
foreach (IParameter param in operation.Parameters)
{
param.In = "formData";
}
operation.Consumes = new List<string>() { "multipart/form-data" };
}
}
And after this everething works as I expect from swagger.
目前这个解决方案对我有用,但感觉不对。也许我缺少一些简单的解决方案。此外,此方法不使用 IFormFile 或其他方式处理 List 或复杂对象属性。