Refitter.SourceGenerator 2.0.0-preview.106

This is a prerelease version of Refitter.SourceGenerator.
dotnet add package Refitter.SourceGenerator --version 2.0.0-preview.106
                    
NuGet\Install-Package Refitter.SourceGenerator -Version 2.0.0-preview.106
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Refitter.SourceGenerator" Version="2.0.0-preview.106">
  <PrivateAssets>all</PrivateAssets>
  <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Refitter.SourceGenerator" Version="2.0.0-preview.106" />
                    
Directory.Packages.props
<PackageReference Include="Refitter.SourceGenerator">
  <PrivateAssets>all</PrivateAssets>
  <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Refitter.SourceGenerator --version 2.0.0-preview.106
                    
#r "nuget: Refitter.SourceGenerator, 2.0.0-preview.106"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Refitter.SourceGenerator@2.0.0-preview.106
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Refitter.SourceGenerator&version=2.0.0-preview.106&prerelease
                    
Install as a Cake Addin
#tool nuget:?package=Refitter.SourceGenerator&version=2.0.0-preview.106&prerelease
                    
Install as a Cake Tool

Source Generator

Recommendation: Consider using Refitter.MSBuild instead to ensure that the code is generated pre-compile which allows the Refit source generator to work without rebuilding the project.

Refitter is available as a C# Source Generator that uses the Refitter.Core library for generating a REST API Client using the Refit library. Refitter can generate the Refit interface from OpenAPI specifications. Refitter could format the generated Refit interface to be managed by Apizr (v6+) and generate some registration helpers too.

Starting with v2.0.0, the source generator emits code in-memory through Roslyn AddSource() instead of writing .g.cs files to disk. Use your IDE's generated-files view to inspect the output. If your workflow requires physical generated files for review, commits, or build scripts, use Refitter CLI or Refitter.MSBuild instead.

Installation

The source generator is distributed as a NuGet package and should be installed to the project that will contain the generated code

dotnet add package Refitter.SourceGenerator
dotnet add package Refit

Refitter.SourceGenerator keeps its Refit dependency private, so consuming projects must add their own direct package reference to Refit. If you use generated dependency-injection helpers such as ConfigureRefitClients(), also add Refit.HttpClientFactory explicitly.

Usage

This source generator generates code based on any .refitter file included to the project as AdditionalFiles.

The generator can automatically detect all .refitter files inside the project that referenced the Refitter.SourceGenerator package and there is no need to include them manually as AdditionalFiles

.Refitter File format

The following is an example .refitter file

{
  "openApiPath": "/path/to/your/openAPI", // Required if openApiPaths is not specified
  "namespace": "Org.System.Service.Api.GeneratedCode", // Optional. Default=GeneratedCode
  "contractsNamespace": "Org.System.Service.Api.GeneratedCode.Contracts", // Optional. Default=GeneratedCode
  "naming": {
    "useOpenApiTitle": false, // Optional. Default=true
    "interfaceName": "MyApiClient" // Optional. Default=ApiClient
  },
  "generateContracts": true, // Optional. Default=true
  "generateClients": true, // Optional. Default=true
  "generateXmlDocCodeComments": true, // Optional. Default=true
  "generateStatusCodeComments": true, // Optional. Default=true
  "addAutoGeneratedHeader": true, // Optional. Default=true
  "addAcceptHeaders": true, // Optional. Default=true
  "addContentTypeHeaders": true, // Optional. Default=true
  "returnIApiResponse": false, // Optional. Default=false
  "responseTypeOverride": { // Optional. Default={}
    "File_Upload": "IApiResponse",
    "File_Download": "System.Net.Http.HttpContent"
  },
  "generateOperationHeaders": true, // Optional. Default=true
  "ignoredOperationHeaders": ["apiKey"], // Optional. Default=[]
  "typeAccessibility": "Public", // Optional. Values=Public|Internal. Default=Public
  "useCancellationTokens": false, // Optional. Default=false
  "useIsoDateFormat": false, // Optional. Default=false
  "multipleInterfaces": "ByEndpoint", // Optional. May be one of "ByEndpoint" or "ByTag"
  "generateDeprecatedOperations": false, // Optional. Default=true
  "operationNameTemplate": "{operationName}Async", // Optional. Must contain {operationName}. When multipleInterfaces == "ByEndpoint", this is name of the Execute() method in the interface where all instances of the string '{operationName}' is replaced with 'Execute'
  "optionalParameters": false, // Optional. Default=false
  "outputFolder": "../CustomOutput" // Optional. Default=./Generated
  "outputFilename": "RefitInterface.cs", // Optional. Default=Output.cs for CLI tool
  "contractsOutputFolder": "../Contracts", // Optional. Default=NULL
  "generateMultipleFiles": false, // Optional. Default=false
  "additionalNamespaces": [ // Optional
    "Namespace1",
    "Namespace2"
  ],
  "excludeNamespaces": [ // Optional. Exclude namespaces that match the provided regular expressions
    "^Namespace[.].*",
    "^Namespace$"
  ],
  "includeTags": [ // Optional. OpenAPI Tag to include when generating code
    "Pet",
    "Store",
    "User"
  ],
  "includePathMatches": [ // Optional. Only include Paths that match the provided regular expression
    "^/pet/.*",
    "^/store/.*"
  ],
  "trimUnusedSchema": false, // Optional. Default=false
  "keepSchemaPatterns": [ // Optional. Force to keep matching schema, uses regular expressions. Use together with trimUnusedSchema=true
    "^Model$",
    "^Person.+"
  ],
  "includeInheritanceHierarchy": false, // Optional. Default=false. Set to true to keep all possible type-instances of inheritance/union types. This works in conjunction with trimUnusedSchema.
  "generateDefaultAdditionalProperties": true, // Optional. default=true
  "operationNameGenerator": "Default", // Optional. May be one of Default, MultipleClientsFromOperationId, MultipleClientsFromPathSegments, MultipleClientsFromFirstTagAndOperationId, MultipleClientsFromFirstTagAndOperationName, MultipleClientsFromFirstTagAndPathSegments, SingleClientFromOperationId, SingleClientFromPathSegments
  "immutableRecords": false,
  "useDynamicQuerystringParameters": true, // Optional. Default=false
  "usePolymorphicSerialization": true, // Optional. Default=false
  "generateDisposableClients": true, // Optional. Default=false
  "dependencyInjectionSettings": { // Optional
    "baseUrl": "https://petstore3.swagger.io/api/v3", // Optional. Leave this blank to set the base address manually
    "httpMessageHandlers": [ // Optional
        "AuthorizationMessageHandler",
        "TelemetryMessageHandler"
    ],
    "transientErrorHandler": "Polly", // Optional. Value=None|Polly|HttpResilience
    "maxRetryCount": 3, // Optional. Default=6
    "firstBackoffRetryInSeconds": 0.5 // Optional. Default=1.0
  },
  "apizrSettings": { // Optional
    "withRequestOptions": true, // Optional. Default=true
    "withRegistrationHelper": true, // Optional. Default=false
    "withCacheProvider": "InMemory", // Optional. Values=None|Akavache|MonkeyCache|InMemory|DistributedAsString|DistributedAsByteArray. Default=None
    "withPriority": true, // Optional. Default=false
    "withMediation": true, // Optional. Default=false
    "withOptionalMediation": true, // Optional. Default=false
    "withMappingProvider": "AutoMapper", // Optional. Values=None|AutoMapper|Mapster. Default=None
    "withFileTransfer": true // Optional. Default=false
  },
  "codeGeneratorSettings": { // Optional. Default settings are the values set in this example
    "requiredPropertiesMustBeDefined": true,
    "generateDataAnnotations": true,
    "anyType": "object",
    "dateType": "System.DateTimeOffset",
    "dateTimeType": "System.DateTimeOffset",
    "timeType": "System.TimeSpan",
    "timeSpanType": "System.TimeSpan",
    "arrayType": "System.Collections.Generic.ICollection",
    "dictionaryType": "System.Collections.Generic.IDictionary",
    "arrayInstanceType": "System.Collections.ObjectModel.Collection",
    "dictionaryInstanceType": "System.Collections.Generic.Dictionary",
    "arrayBaseType": "System.Collections.ObjectModel.Collection",
    "dictionaryBaseType": "System.Collections.Generic.Dictionary",
    "integerType": "Int32", // Optional. Default="Int32". The .NET type for OpenAPI integers without a format. Possible values: "Int32", "Int64"
    "propertySetterAccessModifier": "",
    "generateImmutableArrayProperties": false,
    "generateImmutableDictionaryProperties": false,
    "handleReferences": false,
    "jsonSerializerSettingsTransformationMethod": null,
    "generateJsonMethods": false,
    "enforceFlagEnums": false,
    "inlineNamedDictionaries": false,
    "inlineNamedTuples": true,
    "inlineNamedArrays": false,
    "generateOptionalPropertiesAsNullable": false,
    "generateNullableReferenceTypes": false,
    "generateNativeRecords": false,
    "generateDefaultValues": true,
    "inlineNamedAny": false,
    "inlineJsonConverters": true, // Optional. Default=true. Set to false to not generate JsonConverter attributes for enum properties
    "dateFormat": "yyyy-MM-dd",
    "dateTimeFormat": "yyyy-MM-dd",
    "excludedTypeNames": [
      "ExcludedTypeFoo",
      "ExcludedTypeBar"
    ],
    "customTemplateDirectory": "./path/to/directory/" // Optional. See <https://github.com/RicoSuter/NSwag/wiki/Templates>
  }
}

The following is an example .refitter file using multiple OpenAPI specifications that are merged into a single client

{
  "openApiPaths": [ // Required if openApiPath is not specified. Documents are merged; first spec wins on duplicates
    "/path/to/your/openAPI/v1",
    "/path/to/your/openAPI/v2"
  ],
  "namespace": "Org.System.Service.Api.GeneratedCode"
}
  • openApiPath - points to the OpenAPI Specifications file. This can be the path to a file stored on disk, relative to the .refitter file. This can also be a URL to a remote file that will be downloaded over HTTP/HTTPS. Required if openApiPaths is not specified.
  • openApiPaths - an array of paths to multiple OpenAPI Specifications files. When specified, the documents are merged into a single client. The first document in the array serves as the base; paths, component schemas, definitions (OpenAPI 2.x), and tags from subsequent documents are merged in. When duplicates exist (same path key or schema name), the first document's entry is preserved. Use this instead of openApiPath when you want to generate a single client from multiple API versions. Required if openApiPath is not specified.
  • namespace - the namespace used in the generated code. If not specified, this defaults to GeneratedCode
  • contractsNamespace - the namespace used for generated contracts. If not specified, this defaults to GeneratedCode
  • naming.useOpenApiTitle - a boolean indicating whether the OpenApi title should be used. Default is true
  • naming.interfaceName - the name of the generated interface. The generated code will automatically prefix this with I so if this set to MyApiClient then the generated interface is called IMyApiClient. Default is ApiClient
  • generateContracts - a boolean indicating whether contracts should be generated. A use case for this is several API clients use the same contracts. Default is true
  • generateClients - a boolean indicating whether clients should be generated. A use case for this is to separate clients and contracts into two separate generation runs. Default is true
  • generateXmlDocCodeComments - a boolean indicating whether XML doc comments should be generated. Default is true
  • generateStatusCodeComments - a boolean indicating whether the XML docs for ApiException and IApiResponse contain detailed descriptions for every documented status code. Default is true
  • addAutoGeneratedHeader - a boolean indicating whether XML doc comments should be generated. Default is true
  • addAcceptHeaders - a boolean indicating whether to add accept headers [Headers("Accept: application/json")]. Default is true
  • addContentTypeHeaders - a boolean indicating whether to add content type headers [Headers("Content-Type: application/json")]. Default is true
  • returnIApiResponse - a boolean indicating whether to return IApiResponse<T> objects. Default is false
  • responseTypeOverride - a dictionary with operation ids (as specified in the OpenAPI document) and a particular return type to use. The types are wrapped in a task, but otherwise unmodified (so make sure to specify or import their namespaces). Default is {}
  • generateOperationHeaders - a boolean indicating whether to use operation headers in the generated methods. Default is true
  • ignoredOperationHeaders - A collection of headers to omit from operation signatures. Default is []
  • typeAccessibility - the generated type accessibility. Possible values are Public and Internal. Default is Public
  • useCancellationTokens - Use cancellation tokens in the generated methods. Default is false
  • useIsoDateFormat - Set to true to explicitly format date query string parameters in ISO 8601 standard date format using delimiters (for example: 2023-06-15). Default is false
  • multipleInterfaces - Set to ByEndpoint to generate an interface for each endpoint, or ByTag to group Endpoints by their Tag (like SwaggerUI groups them).
  • outputFolder - a relative output folder used by Refitter CLI and Refitter.MSBuild. The source generator emits code in-memory and does not write to this folder. Default is ./Generated
  • outputFilename - Output filename when used from the CLI tool. For the source generator, this sets the base Roslyn hint name for the in-memory generated source; when omitted it derives from the .refitter filename.
  • contractsOutputFolder - a relative contracts output folder used by Refitter CLI and Refitter.MSBuild. The source generator emits contracts in-memory, so this setting has no effect there. Default is NULL
  • generateMultipleFiles - generates multiple disk files when used by Refitter CLI or Refitter.MSBuild. The source generator currently emits a single in-memory source addition per .refitter file, so this does not produce separate physical files there. Default is false
  • additionalNamespaces - A collection of additional namespaces to include in the generated file. A use case for this is when you want to reuse contracts from a different namespace than the generated code. Default is empty
  • excludeNamespaces - A collection of regular expressions to exclude namespaces from the generated file. A use case for this is when your project has global usings where these namespaces would be redundant. Default is empty
  • includeTags - A collection of tags to use a filter for including endpoints that contain this tag.
  • includePathMatches - A collection of regular expressions used to filter paths.
  • generateDeprecatedOperations - a boolean indicating whether deprecated operations should be generated or skipped. Default is true
  • operationNameTemplate - Generate operation names using pattern. This must contain the string {operationName}. An example usage of this could be {operationName}Async to suffix all method names with Async. When using multiple interfaces with ByEndpoint, this is name of the Execute() method in the interface where all instances of the string '{operationName}' is replaced with 'Execute'
  • optionalParameters - Generate non-required parameters as nullable optional parameters
  • trimUnusedSchema - Removes unreferenced components schema to keep the generated output to a minimum
  • keepSchemaPatterns: A collection of regular expressions to force to keep matching schema. This is used together with trimUnusedSchema
  • includeInheritanceHierarchy: Set to true to keep all possible type-instances of inheritance/union types. If this is false only directly referenced types will be kept. This works in conjunction with trimUnusedSchema. Default is false
  • generateDefaultAdditionalProperties: Set to false to skip default additional properties. Default is true
  • operationNameGenerator: The NSwag IOperationNameGenerator implementation to use. See https://refitter.github.io/api/Refitter.Core.OperationNameGeneratorTypes.html
  • immutableRecords: Set to true to generate contracts as immutable records instead of classes. Default is false
  • useDynamicQuerystringParameters: Set to true to wrap multiple query parameters into a single complex one. Default is false (no wrapping). See https://github.com/reactiveui/refit?tab=readme-ov-file#dynamic-querystring-parameters for more information.
  • dependencyInjectionSettings - Setting this will generated extension methods to IServiceCollection for configuring Refit clients
    • baseUrl - Used as the HttpClient base address. Leave this blank to manually set the base URL
    • httpMessageHandlers - A collection of HttpMessageHandler that is added to the HttpClient pipeline
    • transientErrorHandler - This is the transient error handler to use. Possible values are None, Polly, and HttpResilience. Default is None
    • maxRetryCount - This is the max retry count used in the Polly retry policy. Default is 6
    • firstBackoffRetryInSeconds - This is the duration of the initial retry backoff. Default is 1 second
  • apizrSettings - Setting this will format Refit interface to be managed by Apizr. See https://www.apizr.net for more information
    • withRequestOptions - Tells if the Refit interface methods should have a final IApizrRequestOptions options parameter
    • withRegistrationHelper - Tells if Refitter should generate Apizr registration helpers (extended with dependencyInjectionSettings set, otherwise static)
    • withCacheProvider - Set the cache provider to be used
    • withPriority - Tells if Apizr should handle request priority
    • withMediation - Tells if Apizr should handle request mediation (extended only)
    • withOptionalMediation - Tells if Apizr should handle optional request mediation (extended only)
    • withMappingProvider - Set the mapping provider to be used
    • withFileTransfer - Tells if Apizr should handle file transfer
  • codeGeneratorSettings - Setting this allows customization of the NSwag generated types and contracts
    • requiredPropertiesMustBeDefined - Default is true,
    • generateDataAnnotations - Default is true,
    • anyType - Default is object,
    • dateType - Default is System.DateTimeOffset,
    • dateTimeType - Default is System.DateTimeOffset,
    • timeType - Default is System.TimeSpan,
    • timeSpanType - Default is System.TimeSpan,
    • arrayType - Default is System.Collections.Generic.ICollection,
    • dictionaryType - Default is System.Collections.Generic.IDictionary,
    • arrayInstanceType - Default is System.Collections.ObjectModel.Collection,
    • dictionaryInstanceType - Default is System.Collections.Generic.Dictionary,
    • arrayBaseType - Default is System.Collections.ObjectModel.Collection,
    • dictionaryBaseType - Default is System.Collections.Generic.Dictionary,
    • integerType - Default is Int32. The .NET type to use for OpenAPI integer types without a format specifier. Possible values: Int32, Int64
    • propertySetterAccessModifier - Default is ``,
    • generateImmutableArrayProperties - Default is false,
    • generateImmutableDictionaryProperties - Default is false,
    • handleReferences - Default is false,
    • jsonSerializerSettingsTransformationMethod - Default is null,
    • generateJsonMethods - Default is false,
    • enforceFlagEnums - Default is false,
    • inlineNamedDictionaries - Default is false,
    • inlineNamedTuples - Default is true,
    • inlineNamedArrays - Default is false,
    • generateOptionalPropertiesAsNullable - Default is false,
    • generateNullableReferenceTypes - Default is false,
    • generateNativeRecords - Default is false
    • generateDefaultValues - Default is true
    • inlineNamedAny - Default is false
    • inlineJsonConverters - Default is true. When set to false, enum properties will not have [JsonConverter(typeof(JsonStringEnumConverter))] attributes
    • dateFormat - Default is null
    • dateTimeFormat - Default is null
    • excludedTypeNames - Default is empty
    • customTemplateDirectory - Custom directory with NSwag fluid templates for code generation. Default is null which uses the default NSwag templates. See https://github.com/RicoSuter/NSwag/wiki/Templates
There are no supported framework assets in this package.

Learn more about Target Frameworks and .NET Standard.

  • .NETStandard 2.0

    • No dependencies.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
2.0.0-preview.106 34 4/26/2026
2.0.0-preview.105 39 4/21/2026
1.8.0-preview.104 41 4/21/2026
1.8.0-preview.103 43 4/17/2026
1.8.0-preview.102 50 4/7/2026
1.8.0-preview.101 58 3/27/2026
1.8.0-preview.100 56 3/26/2026
1.8.0-preview.99 58 3/8/2026
1.7.3 11,958 1/25/2026
1.7.3-preview.98 66 1/23/2026
1.7.3-preview.97 53 1/23/2026
1.7.3-preview.96 54 1/23/2026
1.7.3-preview.95 52 1/23/2026
1.7.3-preview.94 56 1/23/2026
1.7.3-preview.93 54 1/23/2026
1.7.3-preview.92 58 1/23/2026
1.7.3-preview.91 60 1/23/2026
1.7.3-preview.89 56 1/23/2026
1.7.3-preview.88 58 1/23/2026
1.7.2 740 1/21/2026
Loading failed