Swagger UI,multipart/form-data 中的对象数组

Swagger UI, array of objects in multipart/form-data

我有一个 multipart/form-data 格式的 PUT 查询。

我需要发送 class 的对象数组。 class 看起来像:

    public class TestObjects
    {
       public long Id { get; set; }

       public string Name { get; set; }

       public decimal MaxScore { get; set; }
    }

这个招摇场应该写什么?

它是 github 上的 known issue,它似乎仍未修复(我也尝试过 .NET 6)。

您需要输入如下数据:

然后自定义模型活页夹如下:

public class MetadataValueModelBinder : IModelBinder
{
    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        if (bindingContext == null)
            throw new ArgumentNullException(nameof(bindingContext));

        var values = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

        if (values.Length == 0)
            return Task.CompletedTask;
        var options = new JsonSerializerOptions() { PropertyNameCaseInsensitive = true };

        var deserialized = JsonSerializer.Deserialize(values.FirstValue, bindingContext.ModelType, options);

        bindingContext.Result = ModelBindingResult.Success(deserialized);
        return Task.CompletedTask;
    }
}

将模型绑定器添加到模型中class:

[ModelBinder(BinderType = typeof(MetadataValueModelBinder))]
public class TestObjects
{
    public long Id { get; set; }

    public string Name { get; set; }

    public decimal MaxScore { get; set; }
}

可以看到schema示例没有显示示例,如果要显示示例还需要自定义IOperationFilter:

public class CustomOperationFilter : IOperationFilter
{
    public void Apply(OpenApiOperation operation, OperationFilterContext context)
    {
        
        if (operation.RequestBody!=null && operation.RequestBody.Content.TryGetValue("multipart/form-data", out var openApiMediaType))
        {
            var options = new JsonSerializerOptions { WriteIndented = true };
            var array = new OpenApiArray
             {
            new OpenApiString(JsonSerializer.Serialize(new TestObjects {Id = 0, Name="string",MaxScore=0}, options)),
             };

            openApiMediaType.Schema.Properties["Competences"].Example = array;
        }
    }
}

注册 IOperationFilter:

services.AddSwaggerGen(c =>
{
    c.OperationFilter<CustomOperationFilter>();
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "WebApi5_0", Version = "v1" });
});

另一种解决方法是您可以使用 [FromBody] 而不是 [FromForm]:

[HttpPut]
public void Post([FromBody] List<TestObjects> Competences)
{

}

输入如下 json 数据:

[
  {
    "id": 1,
    "name": "aa",
    "maxScore": 1
  },
  {
    "id": 2,
    "name": "bb",
    "maxScore": 2
  }
]

结果: