【问题标题】:Swagger UI, array of objects in multipart/form-dataSwagger UI,multipart/form-data 中的对象数组
【发布时间】:2022-01-04 13:00:50
【问题描述】:

我有一个多部分/表单数据格式的 PUT 查询。

我需要发送一个类对象数组。 该类看起来像:

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

       public string Name { get; set; }

       public decimal MaxScore { get; set; }
    }

我应该在这个大摇大摆的领域写什么?

【问题讨论】:

    标签: c# asp.net-core swagger swagger-ui webapi


    【解决方案1】:

    这是 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;
        }
    }
    

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

    [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
      }
    ]
    

    结果:

    【讨论】:

    • 非常感谢!
    猜你喜欢
    • 2019-04-12
    • 1970-01-01
    • 1970-01-01
    • 2020-11-08
    • 2019-06-10
    • 1970-01-01
    • 2013-09-24
    • 2017-01-12
    • 2019-10-31
    相关资源
    最近更新 更多