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

使用dotnet swagger本地生成Swagger文件时的配置异常排查

生成Swagger文件时Guid格式错误的解决方法

问题场景

执行本地生成Swagger文件的命令:

dotnet swagger tofile --output swagger.json Proj1.dll v1

触发以下格式异常:

Unhandled exception. System.FormatException: Guid should contain 32 digits with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).
   at System.Guid.GuidResult.SetFailure(Boolean overflow, String failureMessageID)
   at System.Guid.TryParseExactD(ReadOnlySpan`1 guidString, GuidResult& result)
   at System.Guid.TryParseGuid(ReadOnlySpan`1 guidString, GuidResult& result)
   at System.Guid..ctor(String g)
   at Basic.Configuration.SettingsExtension.ApplyLoggingConfiguration(IServiceCollection services, IConfiguration configuration, String connectionStringKey) in C:\Users\person1\source\repos\Proj1\Proj1.Core\Basic.cs:line 383

异常触发自代码中尝试将配置项Guid1转换为Guid的逻辑:

namespace Configuration
{
    public static class SettingsExtension
    {
        public static void ApplyLoggingConfiguration(this IServiceCollection services, IConfiguration configuration, string connectionStringKey)
        {
            AppSettings.Core.SomeKey = new Guid(configuration["Guid1"]);

当前appsettings.json的对应配置:

{
  "Guid1": "00000000-0000-0000-0000-00000000",
}

解决步骤

  • 修正Guid格式:标准Guid格式为xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx(8-4-4-4-12位字符,含4个横杠),你配置的00000000-0000-0000-0000-00000000最后一段仅8位,不符合要求,应修改为:
    {
      "Guid1": "00000000-0000-0000-0000-000000000000"
    }
    
  • 确保配置文件被正确加载:执行dotnet swagger命令时,需保证命令所在目录下存在appsettings.json(或对应环境的配置文件)。如果配置文件在其他目录,可将其复制到命令执行目录,或者通过指定环境变量、配置参数让程序加载正确的配置文件。
  • 增加格式校验逻辑:代码中直接调用new Guid()会在格式错误时崩溃,建议替换为安全解析逻辑,提前处理异常:
    if (!Guid.TryParse(configuration["Guid1"], out var someKeyGuid))
    {
        throw new InvalidOperationException("配置项Guid1格式无效,请检查appsettings.json");
        // 或设置默认值:someKeyGuid = Guid.Empty;
    }
    AppSettings.Core.SomeKey = someKeyGuid;
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 09:20:30