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

.NET Core 7 WorkerService作为Windows服务时JSON反序列化失败

.NET Core 7 WorkerService Windows服务运行时JSON反序列化异常问题

问题场景

我们正在开发.NET Core 7 WorkerService,该服务从文件读取JSON并反序列化为MWRoot模型:

模型定义

public class MWRoot
{
    public string? Authority { get; set; }
    public string? ShopNo { get; set; }
}

JSON内容

{
    "Authority": "lbg",
    "ShopNo": "1397"
}

反序列化代码

using (StreamReader r = new StreamReader(jsonfile, true))
{
    string json = r.ReadToEnd();        
    MWRoot mwProperty = JsonSerializer.Deserialize<MWRoot>(json);                    
} 

在Visual Studio 2022中调试程序无问题,但通过sc create "ServiceName" binpath=.....命令将其注册为Windows服务运行时,抛出异常:

不支持对无参数构造函数、单一参数构造函数或未使用JsonConstructorAttribute标记的参数化构造函数的类型进行反序列化。

解决方案

  • 显式添加无参数构造函数:虽然C# 9+自动属性类会隐式生成无参数构造函数,但Windows服务运行环境的序列化上下文可能无法识别该隐式构造函数。手动添加无参数构造函数即可解决:

    public class MWRoot
    {
        // 显式添加无参数构造函数
        public MWRoot() {}
        public string? Authority { get; set; }
        public string? ShopNo { get; set; }
    }
    
  • 检查发布模式与剪裁设置:如果服务是通过剪裁发布部署的,可能导致反射相关的构造函数信息被移除。修改项目发布配置,禁用剪裁功能:
    在项目文件(.csproj)中添加或修改以下配置:

    <PropertyGroup>
        <PublishTrimmed>false</PublishTrimmed>
    </PropertyGroup>
    
  • 确认JSON序列化选项:确保反序列化时未配置限制无参数构造函数的选项,保持JsonSerializerOptions默认配置即可,避免设置会干扰构造函数识别的参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 07:12:39