提问人:MohanmadJavad Jamali 提问时间:10/16/2023 最后编辑:marc_sMohanmadJavad Jamali 更新时间:10/16/2023 访问量:77
来自 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]
问:
我在将 multipart/form-data 请求中的对象列表绑定到相关 C# 类属性的模型绑定器时遇到了问题。
这是我在 Swagger 中的请求:
在我的操作方法中,计数为 0:ProductAttributes
但我预计计数为 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)
{
// ...
}
答:
0赞
Ruikai Feng
10/16/2023
#1
您应该使用 postman 发送键值对,如下所示:
对于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; }
}
结果:
评论
ProductAttributes
ProductAttributes.0.attributeId
ProductAttributes.0.value
[FromBody]