You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 8 Blazor WASM发布后出现KeyValuePair反序列化异常

解决.NET 8 Blazor WASM发布后KeyValuePair反序列化异常

问题核心原因

发布Blazor WASM应用时,.NET 8默认启用的ILLink裁剪优化会移除KeyValuePair<string, string>构造函数的参数名称,导致System.Text.Json无法正确识别参数完成反序列化。而本地Debug/Release模式、LinqPad环境未启用该裁剪优化,因此不会触发错误。


解决方案

方案1:使用源生成序列化器(官方推荐)

通过源生成器提前生成序列化代码,彻底规避ILLink裁剪带来的参数名称丢失问题。

  1. 创建序列化上下文类:
using System.Text.Json.Serialization;

[JsonSerializable(typeof(List<KeyValuePair<string, string>>))]
public partial class AppJsonSerializerContext : JsonSerializerContext
{
}
  1. 修改反序列化代码:
var options = new JsonSerializerOptions
{
    PropertyNameCaseInsensitive = true,
    TypeInfoResolver = AppJsonSerializerContext.Default
};

List<KeyValuePair<string, string>> items = JsonSerializer.Deserialize<List<KeyValuePair<string, string>>>(data, options)!;

方案2:配置ILLink保留KeyValuePair的参数名称

在项目文件(.csproj)中添加配置,阻止裁剪工具移除KeyValuePair构造函数的参数名称:

<ItemGroup>
  <TrimmerDescriptor Include="KeyValuePairTrim">
    <Descriptor>
      <Type Name="System.Collections.Generic.KeyValuePair`2">
        <Method Name=".ctor" KeepParameterNames="true" />
      </Type>
    </Descriptor>
  </TrimmerDescriptor>
</ItemGroup>

方案3:替换KeyValuePair为自定义类型或Dictionary

如果不想修改序列化配置,可以改用自定义类存储键值对:

public class KeyValueItem
{
    public string Key { get; set; } = string.Empty;
    public string Value { get; set; } = string.Empty;
}

反序列化代码修改为:

JsonSerializerOptions options = new() { PropertyNameCaseInsensitive = true };
List<KeyValueItem> items = JsonSerializer.Deserialize<List<KeyValueItem>>(data, options)!;

若JSON结构无重复Key,也可直接反序列化为Dictionary<string, string>:

Dictionary<string, string> items = JsonSerializer.Deserialize<Dictionary<string, string>>(data, options)!;

内容的提问来源于stack exchange,提问作者DrGriff

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 10:23:16