[英]C# web api get request fails or adds extra info
我遇到了問題。 我有這些課程。
public class VariantColor
{
public int Id { get; set; }
public string Name { get; set; }
[JsonIgnore]
public IEnumerable<ProductVariant> productVariants { get; set; }
}
public class VariantSize
{
public int Id { get; set; }
public string Name { get; set; }
[JsonIgnore]
public IEnumerable<ProductVariant> productVariants { get; set; }
}
我將它們添加到 dbcontext
public DbSet<VariantColor> variantColors { get; set; }
public DbSet<VariantSize> variantSizes { get; set; }
我在 VariantSizeRepository 中有這個,它工作正常。
public async Task<IEnumerable<VariantSize>> GetAllSizes()
{
var sizes = await _dataContext.variantSizes.ToListAsync();
if(sizes == null)
{
return null;
}
return sizes;
}
但是我在 VariantColorRepository 中有幾乎相同的調用
public async Task<IEnumerable<VariantColor>> GetVariantColors()
{
var colors = _dataContext.variantColors.ToList();
if (colors == null)
{
return null;
}
return colors;
}
如果我使用 ToList() 而不是異步版本,我會收到帶有額外代碼的響應
{
"result": [
{
"id": 1,
"name": "red"
},
{
"id": 2,
"name": "green"
}
],
"id": 242,
"exception": null,
"status": 5,
"isCanceled": false,
"isCompleted": true,
"isCompletedSuccessfully": true,
"creationOptions": 0,
"asyncState": null,
"isFaulted": false
}
如果我使用 ToListAsync() 它會拋出錯誤
System.NotSupportedException: Serialization and deserialization of 'System.Action' instances are not supported. Path: $.MoveNextAction.
---> System.NotSupportedException: Serialization and deserialization of 'System.Action' instances are not supported.
at System.Text.Json.Serialization.Converters.UnsupportedTypeConverter`1.Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
at System.Text.Json.Serialization.Metadata.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
我無法弄清楚問題所在,我將這些調用與 VariiantSizes 進行了相同的調用,但它會拋出錯誤……我做錯了什么?
在這段代碼中
public async Task<IEnumerable<VariantColor>> GetVariantColors()
{
var colors = _dataContext.variantColors.ToList();
if (colors == null)
{
return null;
}
return colors;
}
回報
IEnumerable<VariantColor>
不是
Task<IEnumerable<VariantColor>>
不出所料
改變
var colors = _dataContext.variantColors.ToList();
改為
var colors = await _dataContext.variantColors.ToListAsync();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.