NSwag запустите проект API .NET 8 в Command="$(NSwagExe_Net80) запустите NSwag.json /variables:Configuration=$(Configuration)"

В проекте Dotnet API недавно мы обновляем версию .NET с 6 до 8. В новой версии приложения в файле nswag.json "documentGenerator" двигатель заменен с "webApiToOpenApi" на "aspNetCoreToOpenApi". Вот мой файл nswag.json:

{
  "runtime": "Net80",
  "defaultVariables": "Configuration=Release,OutDir=bin/Release/net8.0/,HomeDir=%USERPROFILE%",
  "documentGenerator": {
    "aspNetCoreToOpenApi": {
      "project": "AppServices.csproj",
      "controllerNames": [],
      "isAspNetCore": true,
      "resolveJsonOptions": false,
      "defaultUrlTemplate": "api/{controller}/{id?}",
      "addMissingPathParameters": false,
      "includedVersions": null,
      "defaultPropertyNameHandling": "CamelCase",
      "defaultReferenceTypeNullHandling": "Null",
      "defaultDictionaryValueReferenceTypeNullHandling": "NotNull",
      "defaultResponseReferenceTypeNullHandling": "Null",
      "defaultEnumHandling": "Integer",
      "flattenInheritanceHierarchy": false,
      "generateKnownTypes": true,
      "generateEnumMappingDescription": false,
      "generateXmlObjects": false,
      "generateAbstractProperties": false,
      "generateAbstractSchemas": true,
      "ignoreObsoleteProperties": false,
      "allowReferencesWithProperties": false,
      "excludedTypeNames": [],
      "serviceHost": null,
      "serviceBasePath": null,
      "serviceSchemes": [],
      "infoTitle": "App Content Services",
      "infoDescription": null,
      "infoVersion": "1.0.0",
      "documentTemplate": null,
      "documentProcessorTypes": [],
      "operationProcessorTypes": [],
      "typeNameGeneratorType": null,
      "schemaNameGeneratorType": null,
      "contractResolverType": null,
      "serializerSettingsType": null,
      "useDocumentProvider": true,
      "documentName": "v1",
      "aspNetCoreEnvironment": null,
      "createWebHostBuilderMethod": null,
      "startupType": null,
      "allowNullableBodyParameters": true,
      "output": null,
      "outputType": "Swagger2",
      "newLineBehavior": "Auto",
      "assemblyPaths": [],
      "assemblyConfig": null,
      "referencePaths": [
        "$(HomeDir)/.nuget/packages"
      ],
      "validateEnums": false,
      "generateEnums": false,
      "msBuildProjectExtensionsPath": null,
      "configuration": null,
      "runtime": null,
      "targetFramework": null,
      "noBuild": true,
      "msBuildOutputPath": null,
      "verbose": true,
      "workingDirectory": null,
      "requireParametersWithoutDefault": false,
      "apiGroupNames": null,
      "useNuGetCache": false
    }
  },
  "codeGenerators": {
    "openApiToCSharpClient": {
      "clientBaseClass": "",
      "configurationClass": "",
      "generateClientClasses": true,
      "generateClientInterfaces": true,
      "clientBaseInterface": null,
      "injectHttpClient": true,
      "disposeHttpClient": true,
      "protectedMethods": [],
      "generateExceptionClasses": true,
      "exceptionClass": "SwaggerException",
      "wrapDtoExceptions": true,
      "useHttpClientCreationMethod": true,
      "httpClientType": "System.Net.Http.HttpClient",
      "useHttpRequestMessageCreationMethod": false,
      "useBaseUrl": false,
      "generateBaseUrlProperty": true,
      "generateSyncMethods": true,
      "generatePrepareRequestAndProcessResponseAsAsyncMethods": false,
      "exposeJsonSerializerSettings": false,
      "clientClassAccessModifier": "public",
      "typeAccessModifier": "public",
      "generateContractsOutput": false,
      "contractsNamespace": null,
      "contractsOutputFilePath": null,
      "parameterDateTimeFormat": "s",
      "parameterDateFormat": "yyyy-MM-dd",
      "generateUpdateJsonSerializerSettingsMethod": true,
      "useRequestAndResponseSerializationSettings": false,
      "serializeTypeInformation": false,
      "queryNullValue": "",
      "className": "{controller}Client",
      "operationGenerationMode": "MultipleClientsFromOperationId",
      "additionalNamespaceUsages": [],
      "additionalContractNamespaceUsages": [],
      "generateOptionalParameters": false,
      "generateJsonMethods": true,
      "enforceFlagEnums": false,
      "parameterArrayType": "System.Collections.Generic.IEnumerable",
      "parameterDictionaryType": "System.Collections.Generic.IDictionary",
      "responseArrayType": "System.Collections.Generic.List",
      "responseDictionaryType": "System.Collections.Generic.Dictionary",
      "wrapResponses": false,
      "wrapResponseMethods": [],
      "generateResponseClasses": true,
      "responseClass": "SwaggerResponse",
      "namespace": "AppService.Clients",
      "requiredPropertiesMustBeDefined": true,
      "dateType": "System.DateTime",
      "jsonConverters": null,
      "anyType": "object",
      "dateTimeType": "System.DateTime",
      "timeType": "System.TimeSpan",
      "timeSpanType": "System.TimeSpan",
      "arrayType": "System.Collections.Generic.List",
      "arrayInstanceType": null,
      "dictionaryType": "System.Collections.Generic.Dictionary",
      "dictionaryInstanceType": null,
      "arrayBaseType": "System.Collections.Generic.List",
      "dictionaryBaseType": "System.Collections.Generic.Dictionary",
      "classStyle": "Inpc",
      "jsonLibrary": "NewtonsoftJson",
      "generateDefaultValues": true,
      "generateDataAnnotations": true,
      "excludedTypeNames": [],
      "excludedParameterNames": [],
      "handleReferences": false,
      "generateImmutableArrayProperties": false,
      "generateImmutableDictionaryProperties": false,
      "jsonSerializerSettingsTransformationMethod": null,
      "inlineNamedArrays": false,
      "inlineNamedDictionaries": false,
      "inlineNamedTuples": true,
      "inlineNamedAny": false,
      "generateDtoTypes": true,
      "generateOptionalPropertiesAsNullable": false,
      "generateNullableReferenceTypes": false,
      "templateDirectory": null,
      "typeNameGeneratorType": null,
      "propertyNameGeneratorType": null,
      "enumNameGeneratorType": null,
      "serviceHost": null,
      "serviceSchemes": null,
      "output": "../AppServices.Clients/GeneratedClients.cs",
      "newLineBehavior": "Auto",
      "validateEnums": false,
      "generateEnums": false
    }
  }
}

Но при выполнении приведенной ниже команды запускается приложение.

<Exec Command = "$(NSwagExe_NET60) run NSwag.json /variables:Configuration=$(Configuration),OutDir=$(OutDir),HomeDir=&quot;$(HomeDir)&quot; " />

и создайте приведенный ниже журнал:

10>NSwag command line tool for .NET Core Net80, toolchain v14.0.7.0 (NJsonSchema v11.0.0.0 (Newtonsoft.Json v13.0.0.0))
10>Visit http://NSwag.org for more information.
10>NSwag bin directory: C:\.....\packages\nswag.msbuild\14.0.7\tools\Net80
10>
10>Executing file 'NSwag.json' with variables 'Configuration=Release,OutDir=bin\Release\net8.0\,HomeDir=C:\Users\MA0021'...
10>Launcher directory: C:\....\.nuget\packages\nswag.msbuild\14.0.7\tools\Net80
10>init main
10>Configuring to Use DbConfigurationSource.
10>info: DbConfigurationProvider[0]
10>      DbConfigurationProvider - Static Logger Configured
10>info: WebHostBootstrapper[0]
10>      WebHostBootstrapper - Static Logger Configured
10>dbug: Microsoft.AspNetCore.Hosting.Diagnostics[3]
10>      Hosting starting
10>dbug: Microsoft.AspNetCore.Mvc.ModelBinding.ModelBinderFactory[12]
10>      Registered model binder providers, in the following order: Microsoft.AspNetCore.Mvc.ModelBinding.......
10>dbug: Microsoft.AspNetCore.Mvc.Razor.Compilation.DefaultViewCompiler[4]
10>      Initializing Razor view compiler with no compiled views.
10>info: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[63]
10>      User profile is available. Using 'C:\.....\ASP.NET\DataProtection-Keys' as key repository and Windows DPAPI to encrypt keys at rest.
10>dbug: Microsoft.AspNetCore.DataProtection.Repositories.FileSystemXmlRepository[37]
10>      Reading data from file 'C:\...\ASP.NET\DataProtection-Keys\key-8b371780-fd9d-496b-bb67-2db2152258dc.xml'.
................
10>dbug: Microsoft.AspNetCore.DataProtection.Internal.DataProtectionHostedService[65]
10>      Key ring with default key {8b371780-fd9d-496b-bb67-2db2152258dc} was loaded during application startup.
10>dbug: Microsoft.AspNetCore.Server.Kestrel[0]
10>      No listening endpoints were configured. Binding to http://localhost:5000 by default.
10>dbug: Microsoft.AspNetCore.Hosting.Diagnostics[4]
10>      Hosting started
10>dbug: Microsoft.AspNetCore.Hosting.Diagnostics[13]
10>      Loaded hosting startup assembly AppServices
10>Hosting environment: Production
10>Content root path: C:\xxxxProj\AppServices
10>Now listening on: http://localhost:5000
10>Application started. Press Ctrl+C to shut down.
10>info: DbConfigurationProvider[0]
10>      DbConfigurationProvider - Static Logger Configured
10>info: WebHostBootstrapper[0]
10>      WebHostBootstrapper - Static Logger Configured
10>trce: DbConfigurationProvider[0]
10>      OnReloadTimerElapsed Triggered
10>Application is shutting down...
10>dbug: Microsoft.AspNetCore.Hosting.Diagnostics[5]
10>      Hosting shutdown
10>Done.
10>
10>Duration: 00:00:34.7767604
10>Done building project "AppServices.csproj".

Пытался добавить параметры ниже в nswag, но приложение все равно запускается. "validateEnums": false, "generateEnums": false,

Что-нибудь не хватает?

Стоит ли изучать PHP в 2026-2027 годах?
Стоит ли изучать PHP в 2026-2027 годах?
Привет всем, сегодня я хочу высказать свои соображения по поводу вопроса, который я уже много раз получал в своем сообществе: "Стоит ли изучать PHP в...
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Приемы CSS-макетирования - floats и Flexbox
Приемы CSS-макетирования - floats и Flexbox
Здравствуйте, друзья-студенты! Готовы совершенствовать свои навыки веб-дизайна? Сегодня в нашем путешествии мы рассмотрим приемы CSS-верстки - в...
Тестирование функциональных ngrx-эффектов в Angular 16 с помощью Jest
В системе управления состояниями ngrx, совместимой с Angular 16, появились функциональные эффекты. Это здорово и делает код определенно легче для...
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Пользовательский скаляр GraphQL
Пользовательский скаляр GraphQL
Листовые узлы системы типов GraphQL называются скалярами. Достигнув скалярного типа, невозможно спуститься дальше по иерархии типов. Скалярный тип...
0
0
544
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

Согласно https://github.com/RicoSuter/NSwag/issues/4524:

i.nswag.json теперь поддерживает только генерацию спецификаций на основе .csproj (удалено на основе отражения/сборки, только aspnetcore2openapi) ii.Удалена команда WebApiToOpenApiCommand: используйте WebApiOpenApiDocumentGenerator для создания собственного проекта контроллеров, ссылающихся на CLI, для создания OpenAPI без запуска приложения.

Надеюсь, это прояснит ваш вопрос.

Другие вопросы по теме