RicoSuter / NSwag

The Swagger/OpenAPI toolchain for .NET, ASP.NET Core and TypeScript.
http://NSwag.org
MIT License
6.62k stars 1.23k forks source link

Could not load type 'NJsonSchema.Annotations.JsonSchemaAttribute' #4790

Closed darix795 closed 3 months ago

darix795 commented 4 months ago

Hello, recently i have upgrade my project to .net 8. Following to this upgrade i move from NSwag 13 to 14. After this NSwag.MSbuild has stopped to work and this is the error stack trace:

NSwag command line tool for .NET Core Net80, toolchain v14.0.3.0 (NJsonSchema v11.0.0.0 (Newtonsoft.Json v13.0.0.0))
  Visit http://NSwag.org for more information.
  NSwag bin directory: /home/vscode/.nuget/packages/nswag.msbuild/14.0.3/tools/Net80
  Executing dotnet exec --depsfile /workspace/src/Api/bin/Debug/net8.0/Licensit.Api.deps.json --runtimeconfig /workspace/src/Api/bin/Debug/net8.0/Licensit.Api.runtimeconfig.json /home/vscode/.nuget/packages/nswag.msbuild/14.0.3/tools/Net80/NSwag.AspNetCore.Launcher.dll /tmp/tmpNz5WPs.tmp /tmp/tmpQteZYn.tmp Licensit.Api /home/vscode/.nuget/packages/nswag.msbuild/14.0.3/tools/Net80/
  Launcher directory: /home/vscode/.nuget/packages/nswag.msbuild/14.0.3/tools/Net80
  System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.
   ---> System.TypeLoadException: Could not load type 'NJsonSchema.Annotations.JsonSchemaAttribute' from assembly 'NJsonSchema, Version=11.0.0.0, Culture=neutral, PublicKeyToken=c2f9c3bdfae56102'.
     at System.ModuleHandle.ResolveType(QCallModule module, Int32 typeToken, IntPtr* typeInstArgs, Int32 typeInstCount, IntPtr* methodInstArgs, Int32 methodInstCount, ObjectHandleOnStack type)
     at System.ModuleHandle.ResolveTypeHandle(Int32 typeToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext)
     at System.Reflection.RuntimeModule.ResolveType(Int32 metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
     at System.Reflection.CustomAttribute.FilterCustomAttributeRecord(MetadataToken caCtorToken, MetadataImport& scope, RuntimeModule decoratedModule, MetadataToken decoratedToken, RuntimeType attributeFilterType, Boolean mustBeInheritable, ListBuilder`1& derivedAttributes, RuntimeType& attributeType, IRuntimeMethodInfo& ctorWithParameters, Boolean& isVarArg)
     at System.Reflection.CustomAttribute.AddCustomAttributes(ListBuilder`1& attributes, RuntimeModule decoratedModule, Int32 decoratedMetadataToken, RuntimeType attributeFilterType, Boolean mustBeInheritable, ListBuilder`1 derivedAttributes)
     at System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeType type, RuntimeType caType, Boolean inherit)
     at System.Attribute.GetCustomAttributes(MemberInfo element, Boolean inherit)
     at Microsoft.AspNetCore.Mvc.ModelBinding.ModelAttributes.GetAttributesForType(Type type)
     at Microsoft.AspNetCore.Mvc.ModelBinding.ModelAttributes.GetAttributesForParameter(ParameterInfo parameterInfo, Type modelType)
     at Microsoft.AspNetCore.Mvc.ModelBinding.Metadata.DefaultModelMetadataProvider.CreateParameterDetails(ModelMetadataIdentity key)
     at Microsoft.AspNetCore.Mvc.ModelBinding.Metadata.DefaultModelMetadataProvider.CreateCacheEntry(ModelMetadataIdentity key)
     at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
     at Microsoft.AspNetCore.Mvc.ModelBinding.Metadata.DefaultModelMetadataProvider.GetMetadataForParameter(ParameterInfo parameter, Type modelType)
     at Microsoft.AspNetCore.Mvc.ApplicationModels.DefaultApplicationModelProvider.CreateParameterModel(ParameterInfo parameterInfo)
     at Microsoft.AspNetCore.Mvc.ApplicationModels.DefaultApplicationModelProvider.OnProvidersExecuting(ApplicationModelProviderContext context)
     at Microsoft.AspNetCore.Mvc.ApplicationModels.ApplicationModelFactory.CreateApplicationModel(IEnumerable`1 controllerTypes)
     at Microsoft.AspNetCore.Mvc.ApplicationModels.ControllerActionDescriptorProvider.GetDescriptors()
     at Microsoft.AspNetCore.Mvc.ApplicationModels.ControllerActionDescriptorProvider.OnProvidersExecuting(ActionDescriptorProviderContext context)
     at Microsoft.AspNetCore.Mvc.Infrastructure.DefaultActionDescriptorCollectionProvider.UpdateCollection()
     at Microsoft.AspNetCore.Mvc.Infrastructure.DefaultActionDescriptorCollectionProvider.Initialize()
     at Microsoft.AspNetCore.Mvc.Infrastructure.DefaultActionDescriptorCollectionProvider.get_ActionDescriptors()
     at Microsoft.AspNetCore.Mvc.ApiExplorer.ApiDescriptionGroupCollectionProvider.get_ApiDescriptionGroups()
     at NSwag.Generation.AspNetCore.AspNetCoreOpenApiDocumentGenerator.GenerateAsync(Object serviceProvider)
     at NSwag.AspNetCore.OpenApiDocumentProvider.GenerateAsync(String documentName)
     at NSwag.Commands.Generation.AspNetCore.AspNetCoreToOpenApiCommand.GenerateDocumentWithDocumentProviderAsync(IServiceProvider serviceProvider) in /_/src/NSwag.Commands/Commands/Generation/AspNetCore/AspNetCoreToOpenApiCommand.cs:line 245
     at NSwag.Commands.Generation.AspNetCore.AspNetCoreToOpenApiCommand.GenerateDocumentAsync(IServiceProvider serviceProvider, String currentWorkingDirectory) in /_/src/NSwag.Commands/Commands/Generation/AspNetCore/AspNetCoreToOpenApiCommand.cs:line 239
     at NSwag.Commands.Generation.AspNetCore.AspNetCoreToOpenApiGeneratorCommandEntryPoint.Process(String commandContent, String outputFile, String applicationName) in /_/src/NSwag.Commands/Commands/Generation/AspNetCore/AspNetCoreToOpenApiGeneratorCommandEntryPoint.cs:line 29
     at System.RuntimeMethodHandle.InvokeMethod(Object target, Void** arguments, Signature sig, Boolean isConstructor)
     at System.Reflection.MethodBaseInvoker.InvokeDirectByRefWithFewArgs(Object obj, Span`1 copyOfArgs, BindingFlags invokeAttr)
     --- End of inner exception stack trace ---
     at System.Reflection.MethodBaseInvoker.InvokeDirectByRefWithFewArgs(Object obj, Span`1 copyOfArgs, BindingFlags invokeAttr)
     at System.Reflection.MethodBaseInvoker.InvokeWithFewArgs(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
     at NSwag.AspNetCore.Launcher.Program.Main(String[] args) in /_/src/NSwag.AspNetCore.Launcher/Program.cs:line 132

  Done executing command. Exit Code: 1.
  System.InvalidOperationException: Swagger generation failed with non-zero exit code '1'.
     at NSwag.Commands.Generation.AspNetCore.AspNetCoreToOpenApiCommand.RunAsync(CommandLineProcessor processor, IConsoleHost host) in /_/src/NSwag.Commands/Commands/Generation/AspNetCore/AspNetCoreToOpenApiCommand.cs:line 195
     at NConsole.CommandLineProcessor.ProcessSingleAsync(String[] args, Object input)
     at NConsole.CommandLineProcessor.ProcessAsync(String[] args, Object input)
     at NSwag.Commands.NSwagCommandProcessor.ProcessAsync(String[] args) in /_/src/NSwag.Commands/NSwagCommandProcessor.cs:line 62

Following my csproj configuration:


<Target Name="NSwag" AfterTargets="Build" Condition="'$(DOTNET_RUNNING_IN_CONTAINER)' != 'true' Or '$(DOTNET_RUNNING_IN_DEVCONTAINER)' == 'true'">

    <PropertyGroup>
      <AssemblyPath>$([System.IO.Path]::GetFullPath('$(OutDir)Licensit.Api.dll'))</AssemblyPath>
      <SwaggerPath>$([System.IO.Path]::GetFullPath('$(OutDir)swagger.json'))</SwaggerPath>
    </PropertyGroup>

    <Exec Command="$(NSwagExe_Net80) aspnetcore2openapi /documentName:v1 /project:$(ProjectFileName) /nobuild:true /output:$(SwaggerPath)">
      <Output TaskParameter="ExitCode" PropertyName="NSwagExitCode" />
      <Output TaskParameter="ConsoleOutput" PropertyName="NSwagOutput" />
    </Exec>
    <Exec Command="$(NSwagExe_Net80) run nswag.json  /variables:Configuration=$(Configuration)">
      <Output TaskParameter="ExitCode" PropertyName="NSwagExitCode" />
      <Output TaskParameter="ConsoleOutput" PropertyName="NSwagOutput" />
    </Exec>

    <Message Text="$(NSwagOutput)" Condition="'$(NSwagExitCode)' == '0'" Importance="low" />
    <Error Text="$(NSwagOutput)" Condition="'$(NSwagExitCode)' != '0'" />
  </Target>

and version of NSwag packages:

<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
    <PackageReference Include="NJsonSchema" Version="11.0.0" />
    <PackageReference Include="NSwag.AspNetCore" Version="14.0.3" />
    <PackageReference Include="NSwag.MSBuild" Version="14.0.3">
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
      <PrivateAssets>all</PrivateAssets>
    </PackageReference>

At the end i share with you nswag.json file content:

{
  "runtime": "Net80",
  "defaultVariables": null,
  "documentGenerator": {
    "fromDocument": {
      "url": "$(SwaggerPath)",
      "output": null
    }
  },
  "codeGenerators": {
    "openApiToCSharpClient": {
      "output": "../ApiClient/Api.cs",
      "namespace": "Licensit.Api.Client",
      "useBaseUrl": false
    },
    "openApiToTypeScriptClient": {
      "className": "{controller}Client",
      "moduleName": "",
      "namespace": "",
      "typeScriptVersion": 4.1,
      "template": "Fetch",
      "promiseType": "Promise",
      "httpClass": "Http",
      "useSingletonProvider": false,
      "injectionTokenType": "OpaqueToken",
      "rxJsVersion": 6.0,
      "dateTimeType": "Date",
      "nullValue": "Undefined",
      "generateClientClasses": true,
      "generateClientInterfaces": false,
      "generateOptionalParameters": false,
      "exportTypes": true,
      "wrapDtoExceptions": false,
      "exceptionClass": "SwaggerException",
      "extensionCode": "../Webapp/src/Api.extensions.ts",
      "extendedClasses": [
        "SavedQueriesClient",
        "InventoryClient",
        "OrdersClient",
        "QuotesClient",
        "DeadlinesClient"
      ],
      "clientBaseClass": "LicensitClientBase",
      "wrapResponses": true,
      "wrapResponseMethods": [],
      "generateResponseClasses": true,
      "responseClass": "SwaggerResponse",
      "protectedMethods": [],
      "configurationClass": "LicensitClientOptions",
      "useTransformOptionsMethod": true,
      "useTransformResultMethod": false,
      "generateDtoTypes": true,
      "operationGenerationMode": "MultipleClientsFromOperationId",
      "markOptionalProperties": false,
      "generateCloneMethod": false,
      "typeStyle": "Interface",
      "classTypes": [],
      "generateDefaultValues": true,
      "excludedTypeNames": [],
      "excludedParameterNames": [],
      "handleReferences": false,
      "generateConstructorInterface": true,
      "convertConstructorInterfaceData": false,
      "importRequiredTypes": true,
      "useGetBaseUrlMethod": true,
      "baseUrlTokenName": "API_BASE_URL",
      "queryNullValue": "",
      "inlineNamedDictionaries": false,
      "inlineNamedAny": false,
      "templateDirectory": null,
      "typeNameGeneratorType": null,
      "propertyNameGeneratorType": null,
      "enumNameGeneratorType": null,
      "serviceHost": null,
      "serviceSchemes": null,
      "output": "../Webapp/src/Api.ts"
    }
  }
}

I try to install on my project package NJsonSchema.Annotations.JsonSchemaAttribute, but nothing change. Can anyone help me?

kemmis commented 3 months ago

@darix795 did you find a solution for this issue? I'm getting something similar. I updated to .net 8 and from nswag 13->14. After that I started getting:

System.TypeLoadException: Could not load type 'NJsonSchema.Converters.JsonInheritanceConverter' from assembly 'NJsonSchema, Version=11.0.0.0, Culture=neutral, PublicKeyToken=c2f9c3bdfae56102'

RicoSuter commented 3 months ago

Probably you didnt update njs to v11 everywhere as the attributes are now in an own package:

NJsonSchema.Annotations

the newtonsoft inheritance converters are moved to:

NJsonSchema.NewtonsoftJson

(you are probably using stj ones)

kemmis commented 3 months ago

Yep, I had one project that was on 10.9.