来自 multipart/form-data 请求的 ASP.NET Core 7 Web API 中对象的映射列表 [duplicate]

Mapping list of an object in ASP.NET Core 7 Web API from multipart/form-data request [duplicate]

提问人:MohanmadJavad Jamali 提问时间:10/16/2023 最后编辑:marc_sMohanmadJavad Jamali 更新时间:10/16/2023 访问量:77

问:

我在将 multipart/form-data 请求中的对象列表绑定到相关 C# 类属性的模型绑定器时遇到了问题。

这是我在 Swagger 中的请求:

发布请求

请求的其余部分

在我的操作方法中,计数为 0:ProductAttributes

Action 方法

但我预计计数为 2。

我还使用 Postman 测试了 post 请求:

邮差

但结果是一样的。

CreateProductDto类:

public class CreateProductDto
{
    public string Name { get; set; }
    public string Description { get; set; }
    public int QIS { get; set; }
    public decimal Price { get; set; }
    public float DiscountPercentage { get; set; }

    public int CategoryId { get; set; }

    public List<IFormFile> Images { get; set; }
    public List<ProductAttributeCreateDto> ProductAttributes { get; set; }
}

ProductAttributeCreateDto类:

public class ProductAttributeCreateDto
{
    public int AttributeId { get; set; }
    public string Value { get; set; }
}

CreateProduct作用方法:

[HttpPost("CreateProduct")]
public async Task<ActionResult> CreateProduct([FromForm]CreateProductDto createProductDto)
{ 
    // ...
}
C# 多部分表单数据 模型绑定 asp.net-core-7.0

评论

0赞 Yong Shun 10/16/2023
在 Postman 中发送值的方式不正确。它应该是::5,:字符串。它是扁平化的 JSON 表示法ProductAttributesProductAttributes.0.attributeIdProductAttributes.0.value
0赞 Yong Shun 10/16/2023
可能的重复项:.NET Core API - 通过 Postman 将对象数组作为 FormData 发送
0赞 user16606026 10/16/2023
Swagger 在表单中存在枚举问题。我建议使用 json,或者您需要一些解决方法。[FromBody]

答:

0赞 Ruikai Feng 10/16/2023 #1

您应该使用 postman 发送键值对,如下所示:

enter image description here

对于swagger,这是一个已知的问题,直到现在还没有解决,它会发送一个键值对(ProductAttributes-json字符串)而不是上面的键值对,如果你坚持用swagger进行测试,一个解决方法给你:

创建自定义模型联编程序

public class SwaggerArrayBinder : 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(SwaggerArrayBinder))]
    public class ProductAttributeCreateDto
    {
       
        public int AttributeId { get; set; }
        public string Value { get; set; }
    }

结果:

enter image description here