【问题标题】:.NET Core 3.1 CreateHostBuilder Cannot parse JSON file.NET Core 3.1 CreateHostBuilder 无法解析 JSON 文件
【发布时间】:2020-02-11 10:41:50
【问题描述】:

我在尝试运行 ASP.Net Core 3.1 项目时遇到错误。错误在CreateHostBuilderProgram.cs

   public class Program {
        public static void Main(string[] args) {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args).ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });
    }

尚未从 Visual Studio 2019 的默认 ASP.NET Core Web 应用程序模板编辑。它给出了异常

System.FormatException: '无法解析 JSON 文件。'

然而,它并没有准确地引用它无法解析的 JSON 文件。这是pastebin with all 3 existing JSON files it could be parsing.

这是完整的错误堆栈:

  HResult=0x80131537
  Message=Could not parse the JSON file.
  Source=Microsoft.Extensions.Configuration.Json
  StackTrace:
   at Microsoft.Extensions.Configuration.Json.JsonConfigurationProvider.Load(Stream stream)
   at Microsoft.Extensions.Configuration.FileConfigurationProvider.Load(Boolean reload)
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.Extensions.Configuration.FileConfigurationProvider.HandleException(ExceptionDispatchInfo info)
   at Microsoft.Extensions.Configuration.FileConfigurationProvider.Load(Boolean reload)
   at Microsoft.Extensions.Configuration.FileConfigurationProvider.Load()
   at Microsoft.Extensions.Configuration.ConfigurationRoot..ctor(IList`1 providers)
   at Microsoft.Extensions.Configuration.ConfigurationBuilder.Build()
   at Microsoft.Extensions.Hosting.HostBuilder.BuildAppConfiguration()
   at Microsoft.Extensions.Hosting.HostBuilder.Build()
   at <filename>.Main(String[] args) in <filename>:line 13

  This exception was originally thrown at this call stack:
    System.Text.Json.ThrowHelper.ThrowJsonReaderException(ref System.Text.Json.Utf8JsonReader, System.Text.Json.ExceptionResource, byte, System.ReadOnlySpan<byte>)
    System.Text.Json.Utf8JsonReader.ReadSingleSegment()
    System.Text.Json.Utf8JsonReader.Read()
    System.Text.Json.JsonDocument.Parse(System.ReadOnlySpan<byte>, System.Text.Json.Utf8JsonReader, ref System.Text.Json.JsonDocument.MetadataDb, ref System.Text.Json.JsonDocument.StackRowStack)
    System.Text.Json.JsonDocument.Parse(System.ReadOnlyMemory<byte>, System.Text.Json.JsonReaderOptions, byte[])
    System.Text.Json.JsonDocument.Parse(System.ReadOnlyMemory<char>, System.Text.Json.JsonDocumentOptions)
    System.Text.Json.JsonDocument.Parse(string, System.Text.Json.JsonDocumentOptions)
    Microsoft.Extensions.Configuration.Json.JsonConfigurationFileParser.ParseStream(System.IO.Stream)
    Microsoft.Extensions.Configuration.Json.JsonConfigurationProvider.Load(System.IO.Stream)

Inner Exception 1:
JsonReaderException: '{' is an invalid start of a property name. Expected a '"'. LineNumber: 2 | BytePositionInLine: 4

当我开始使用 VS Code 而不是我通常使用的 Visual Studio 时,它就开始了。然而,该项目可以在另一台仅运行 Visual Studio 的 Windows 机器上成功运行。我已经尝试了一些东西,但我没有想法。以下是我尝试过的步骤:

  1. 与其他 2 位同事确认 appsettings.jsonappsettings.Development.jsonlaunchSettings.json 没有在 this thread 中解决的语法错误
  2. 已确认它们都使用 UTF-8 编码,没有 BOM,如 this thread 中所建议的那样
  3. 关闭 Visual Studio 2019,删除 .vs 文件夹,打开然后再次运行
  4. 关闭 Visual Studio Code,删除 .vscode 文件夹,打开然后再次运行
  5. 切换的分支和以前的提交。
  6. 已确认.csproj 中没有用户机密配置
  7. 在本地删除 repo 文件并再次克隆
  8. 完全重启电脑
  9. 在 Visual Studio 中创建新的模板化 ASP.NET Core Web 应用程序。运行成功。
  10. 确认args值是一个大小为[1]的字符串数组。使用 [0] 位置并包含字符串 %LAUNCHER_ARGS%。环境变量不会出现在 app.config 或 Windows 中。我确认args 仍然与测试纯模板项目相同且功能相同。

【问题讨论】:

  • 请告诉我们args的值!听起来 JSON 无效/格式不正确。
  • 这可能是指你的appsettings,你有appsettings文件吗?更重要的是它是validjson吗?
  • args 是一个字符串数组,大小为 [1],[0] 值为 "%LAUNCHER_ARGS%"。我是 .net 核心的新手,所以我不确定这个字符串值是从哪里来的。使用该字符串搜索项目没有结果。 @phuzi
  • @MarkDavies 我可以确认我已经与其他 2 位同事检查了appsettings.json。没有语法错误,但我会在这里发布(带有审查的数据库名称)以确认它。 { "ConnectionStrings": { "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=&lt;azure-db&gt;;Trusted_Connection=True;MultipleActiveResultSets=true" }, "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "AllowedHosts": "*" }
  • 你能告诉我们你对CreateHostBuilder的实现吗?

标签: c# visual-studio visual-studio-code asp.net-core-mvc


【解决方案1】:

听起来不像是破纪录,但任何遇到此问题的人,请确保您的 appsettings.json 格式正确。

我发现在我的情况下,我的连接字符串中没有正确设置转义字符。我没有 .\\MSSQLSERVER,而是 .\MSSQLSERVER。

如果您在本地机器上有一个测试实例,请取出云的连接字符串并将其替换为本地机器的连接字符串(应该更简单),这应该会引导您朝着正确的方向前进。

【讨论】:

  • 您的回答很有帮助,非常感谢
  • 对我来说也一样。非常感谢!
  • 由于某种原因它突然开始出错,这就是原因。但是我检查了我的更改日志,并且不久前检查了具体的更改,所以很奇怪它突然开始了。谢谢!
【解决方案2】:

我在相同版本的 Asp.net Core 上启动 webApi 时遇到了同样的问题。问题是 appsettings.json 中缺少花括号

【讨论】:

    【解决方案3】:

    我最近遇到了这个错误,顶级 cmets 对解决它没有多大帮助。所以首先这个错误 100% 与 JSON 文件格式不正确有关。然而,顶级 cmets 并没有真正告诉您应该检查哪些文件才能找到错误。

    您需要检查以确保其正常工作的文件列表:

    • appsettings.[environment-build](这可能是 99% 的情况的来源)
    • serviceDependencies.[area].json
    • Secrets.json
    • launchSettings.json

    Appsettings 位于您的项目目录中。

    LaunchSettings 和服务依赖项位于您的 Properties 文件夹中。

    Secrets file 最好通过 Connected Services 找到(注意这适用于 Visual Studio)。

    就我而言,我的 Secrets 文件导致了问题。请注意,这并不是每个项目的完整列表,但它至少应该为您指明正确的方向,而不是花费几个小时反复检查您的应用设置文件。

    【讨论】:

      【解决方案4】:

      我遇到了同样的异常,即 JsonReaderException: '}' 在单个 JSON 值之后无效。预期数据结束。行号:13 | BytePositionInLine: 0。

      当我检查 appsettings.json 文件时,我注意到“}”上有一个波浪线。这就是问题所在。原来我的 appsettings.json 文件中有一个额外的“}”。有些可能缺少花括号。放心,问题就在这里。

      【讨论】:

        【解决方案5】:

        我的 appsettings.json 中的值包含一个路径,其中路径中的反斜杠被解释为转义字符,我遇到了问题。

        c:\local-export-folder 更改为c:\\local-export-folder(双反斜杠以避开反斜杠)对我有用。

        我看到您的文件中也有反斜杠。或许试着逃离他们。

        【讨论】:

          【解决方案6】:

          是的,一旦appsettings.json 文件正确更新为:

          {
            "Logging": {
              "LogLevel": {
                "Default": "Warning"
              }
            },
            "AllowedHosts": "*"
          }
          

          【讨论】:

            【解决方案7】:

            在我的例子中,是安装 AWS nuget 后附带的 AWS 设置。在 appSettings.*.json 文件中寻找类似于以下 AWS 配置的内容:

            AWS nuget 添加了以下代码:

            {
              "AWS": {
                "Profile": "local-test-profile",
                "Region": "ap-southeast-1"
              }
            }, 
            

            应该是这样的

              "AWS": {
                "Profile": "local-test-profile",
                "Region": "ap-southeast-1"
              },
            

            【讨论】:

              【解决方案8】:

              尝试通过我们这样的网站验证您的 json 文件:https://jsonlint.com/ 它可以帮助您轻松找到错误。

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2020-05-10
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2020-05-22
                相关资源
                最近更新 更多