在我的Vuex存储中,我创建了包含详细对象的数据对象,然后使用axios将数据发送到后端。我一直收到错误400错误请求
错误消息
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[home_inventory.Models.DTO.Detail]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
正在发送的数据
const data = {
Name: "name",
Detail: {
CategoryId: 1,
Manufactuerer: 1,
Model: "",
SerialNumber: "",
PurchasePlace: "",
Quantity: "",
AcquiredDate: "",
PurchasePrice: "",
CurrentValue: "",
ConditionId: 1,
LocationId: 1,
RetiredDate: "",
Description: ""
}
};
axios.post('https://localhost:5001/api/Assets', data)
.then(res => console.log(res))
.catch(error => console.log(error));
然后我有了我的ASP.Net核心web api后端DTO模型,就像这样http后控制器
[HttpPost]
public async Task<ActionResult> PostAsset([FromBody] AssetSaveRequest assetCreationDto)
{
var asset = _mapper.Map<Asset>(assetCreationDto);
_context.Assets.Add(asset);
//await _context.SaveChangesAsync();
var assetDto = _mapper.Map<AssetDto>(asset);
return CreatedAtAction("GetAsset", new {assetDto.Id}, assetDto);
}
DTO型号
public class AssetSaveRequest
{
public string Name { get; set; }
public List<Detail> Detail { get; set; }
public byte[] Files { get; set; }
}
public class Detail
{
public int CategoryId { get; set; }
public int ManufacturerId { get; set; }
public string Model { get; set; }
public string SerialNumber { get; set; }
public string PurchasePlace { get; set; }
public int Quantity { get; set; }
public DateTime AcquiredDate { get; set; }
public float PurchasePrice { get; set; }
public float CurrentValue { get; set; }
public int ConditionId { get; set; }
public int LocationId { get; set; }
public DateTime RetiredDate { get; set; }
public string Description { get; set; }
}
我不知道如何解决这个问题,让它正确工作。有人能给我任何帮助吗。
任何帮助都是有帮助的。
类似List<Detail>
的.NET List属性对应于JSON中的数组。所以你想把Detail包装成一个数组,比如:
const data = {
Name: "name",
Detail: [
{
CategoryId: 1,
...other values
}
]
};
请注意单个Detail对象周围的方括号。重命名为DetailItems
也会更清楚,它表示一个列表/数组,而不是单个项。