Refitter.SourceGenerator
2.3.2-preview.123
See the version list below for details.
dotnet add package Refitter.SourceGenerator --version 2.3.2-preview.123
NuGet\Install-Package Refitter.SourceGenerator -Version 2.3.2-preview.123
<PackageReference Include="Refitter.SourceGenerator" Version="2.3.2-preview.123"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets> </PackageReference>
<PackageVersion Include="Refitter.SourceGenerator" Version="2.3.2-preview.123" />
<PackageReference Include="Refitter.SourceGenerator"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets> </PackageReference>
paket add Refitter.SourceGenerator --version 2.3.2-preview.123
#r "nuget: Refitter.SourceGenerator, 2.3.2-preview.123"
#:package Refitter.SourceGenerator@2.3.2-preview.123
#addin nuget:?package=Refitter.SourceGenerator&version=2.3.2-preview.123&prerelease
#tool nuget:?package=Refitter.SourceGenerator&version=2.3.2-preview.123&prerelease
Source Generator
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.
The source generator emits code in-memory and also generates the Refit implementations for it, so a single build is enough and nothing needs to be committed to source control.
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
After installing the package, add one or more .refitter files to your project.
Refitter.SourceGenerator automatically includes **/*.refitter as Roslyn AdditionalFiles via its package props, so you do not need to add manual <AdditionalFiles Include="..." /> entries unless you intentionally override that default behavior.
The generated code is added to the compilation in memory, together with the Refit implementations, in a single build. Nothing is written to disk and nothing needs to be committed to source control. The outputFolder, outputFilename, and contractsOutputFolder settings don't create files when using the source generator. To inspect the generated code on disk, set <EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles> in the project file.
How it works with the Refit source generator
Roslyn runs every source generator against the same input, so the Refit source generator can't see the interfaces that Refitter generates. To produce everything in one build, Refitter.SourceGenerator sets DisableRefitSourceGenerator to true for the regular compiler pass and runs the Refit source generator from the project's own Refit package itself, over the project code plus the Refitter output. Hand-written Refit interfaces in the same project are generated as before. Refit analyzer checks that only run while the Refit source generator is enabled, such as RF006 (and RefitRequireGeneratedRequests), are still reported.
For the same reason, when generateJsonSerializerContext is enabled, Refitter also runs the System.Text.Json source generator over the JsonSerializerContext it generates.
If the project sets DisableRefitSourceGenerator to true itself, for example when using Refit.Reflection, Refitter leaves Refit source generation off and only emits its own code.
Telemetry
Refitter.SourceGenerator collects usage telemetry, the same as the Refitter CLI and Refitter.MSBuild. It reports which settings each .refitter file uses and the number of .refitter files in the project, tagged as coming from the source generator, together with a support key. The support key is the same one the Refitter CLI sends: the first 7 characters of a SHA-256 hash of your user name and machine name. Neither name is sent, but the key isn't random, so anyone who knows both names can compute it and match it to your events. Only setting names, boolean and number values, and known enum values (such as multipleInterfaces) are sent. Paths, URLs, namespaces, other text values and comments are redacted and never leave the machine, and settings that Refitter doesn't recognize are only counted, never named.
The source generator itself never makes network calls. Telemetry is sent by a small MSBuild task in the package that runs after the build. It doesn't run in design-time builds (IDE), only sends when the .refitter files or the package version change (it keeps a stamp file in obj), uses a short timeout, and never fails the build.
To opt out, add the following to your .csproj file:
<PropertyGroup>
<RefitterNoLogging>true</RefitterNoLogging>
</PropertyGroup>
Setting the DOTNET_CLI_TELEMETRY_OPTOUT environment variable to 1 or true also disables it.
.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
"returnIAsyncEnumerable": true, // Optional. Default=true. Generate IAsyncEnumerable for streaming responses
"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
"forceAdditionalProperties": false, // Optional. default=false
"operationNameGenerator": "Default", // Optional. May be one of Default, MultipleClientsFromOperationId, MultipleClientsFromPathSegments, MultipleClientsFromFirstTagAndOperationId, MultipleClientsFromFirstTagAndOperationName, MultipleClientsFromFirstTagAndPathSegments, SingleClientFromOperationId, SingleClientFromPathSegments
"immutableRecords": false,
"useDynamicQuerystringParameters": true, // Optional. Default=false
"useMultipartFormObject": false, // 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"
],
"useWindowsAuthentication": true, // Optional. Default=false
"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.refitterfile. This can also be a URL to a remote file that will be downloaded over HTTP/HTTPS. Required ifopenApiPathsis 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 ofopenApiPathwhen you want to generate a single client from multiple API versions. Required ifopenApiPathis not specified.namespace- the namespace used in the generated code. If not specified, this defaults toGeneratedCodecontractsNamespace- the namespace used for generated contracts. If not specified, this defaults toGeneratedCodenaming.useOpenApiTitle- a boolean indicating whether the OpenApi title should be used. Default istruenaming.interfaceName- the name of the generated interface. The generated code will automatically prefix this withIso if this set toMyApiClientthen the generated interface is calledIMyApiClient. Default isApiClientgenerateContracts- a boolean indicating whether contracts should be generated. A use case for this is several API clients use the same contracts. Default istruegenerateClients- 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 istruegenerateXmlDocCodeComments- a boolean indicating whether XML doc comments should be generated. Default istruegenerateStatusCodeComments- a boolean indicating whether the XML docs forApiExceptionandIApiResponsecontain detailed descriptions for every documented status code. Default istrueaddAutoGeneratedHeader- a boolean indicating whether XML doc comments should be generated. Default istrueaddAcceptHeaders- a boolean indicating whether to add accept headers [Headers("Accept: application/json")]. Default istrueaddContentTypeHeaders- a boolean indicating whether to add content type headers [Headers("Content-Type: application/json")]. Default istruereturnIApiResponse- a boolean indicating whether to returnIApiResponse<T>objects. Default isfalsereturnIAsyncEnumerable- a boolean indicating whether streaming responses generateIAsyncEnumerable<T>. Default istrue. Set tofalseto skipIAsyncEnumerable<T>and use the normal configured return type insteadresponseTypeOverride- 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 istrueignoredOperationHeaders- A collection of headers to omit from operation signatures. Default is[]typeAccessibility- the generated type accessibility. Possible values arePublicandInternal. Default isPublicuseCancellationTokens- Use cancellation tokens in the generated methods. Default isfalseuseIsoDateFormat- Set totrueto explicitly format date query string parameters in ISO 8601 standard date format using delimiters (for example: 2023-06-15). Default isfalsemultipleInterfaces- Set toByEndpointto generate an interface for each endpoint, orByTagto group Endpoints by their Tag (like SwaggerUI groups them).outputFolder- not used by the source generator, which doesn't write files to diskoutputFilename- not used by the source generator, which doesn't write files to diskcontractsOutputFolder- not used by the source generator, which doesn't write files to diskgenerateMultipleFiles- splits the generated code into multiple sources. Default isfalseadditionalNamespaces- 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 emptyexcludeNamespaces- 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 emptyincludeTags- 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 istrueoperationNameTemplate- Generate operation names using pattern. This must contain the string {operationName}. An example usage of this could be{operationName}Asyncto suffix all method names with Async. When using multiple interfaces withByEndpoint, 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 parameterstrimUnusedSchema- Removes unreferenced components schema to keep the generated output to a minimumkeepSchemaPatterns: A collection of regular expressions to force to keep matching schema. This is used together withtrimUnusedSchemaincludeInheritanceHierarchy: Set totrueto keep all possible type-instances of inheritance/union types. If this isfalseonly directly referenced types will be kept. This works in conjunction withtrimUnusedSchema. Default isfalsegenerateDefaultAdditionalProperties: Set tofalseto skip default additional properties. Default istrueforceAdditionalProperties: Set totrueto generate additional properties ([JsonExtensionData]) on every contract, even when the schema setsadditionalProperties: false. Useful for read-modify-write clients that must round-trip fields unknown to an older spec. Schema-valued additional properties are left unchanged. Takes precedence overgenerateDefaultAdditionalProperties. Default isfalseoperationNameGenerator: The NSwagIOperationNameGeneratorimplementation to use. See https://refitter.github.io/api/Refitter.Core.OperationNameGeneratorTypes.htmlimmutableRecords: Set totrueto generate contracts as immutable records instead of classes. Default isfalseuseDynamicQuerystringParameters: Set totrueto wrap multiple query parameters into a single complex one. Default isfalse(no wrapping). See https://github.com/reactiveui/refit?tab=readme-ov-file#dynamic-querystring-parameters for more information.useMultipartFormObject: Set totrueto wrap the non-file fields of amultipart/form-datarequest body into a single[FormObject]parameter, so Refit writes each field (including enums) as a plain text part instead of a JSON part. File fields stay as separateStreamPartparameters, and object fields stay as separate parameters sent as JSON parts. Default isfalse(no wrapping). Requires theRefit.Reflectionpackage and is not supported byAddRefitGeneratedClientor NativeAOT. See https://www.reactiveui.net/documentation/refit/requests/multipart/#flatten-a-form-object-reflection-only-path for more information.dependencyInjectionSettings- Setting this will generated extension methods toIServiceCollectionfor configuring Refit clients, including optional Windows Authentication supportbaseUrl- Used as the HttpClient base address. Leave this blank to manually set the base URLhttpMessageHandlers- A collection ofHttpMessageHandlerthat is added to the HttpClient pipelinetransientErrorHandler- This is the transient error handler to use. Possible values areNone,Polly, andHttpResilience. Default isNonemaxRetryCount- This is the max retry count used in the Polly retry policy. Default is 6firstBackoffRetryInSeconds- 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 informationwithRequestOptions- Tells if the Refit interface methods should have a final IApizrRequestOptions options parameterwithRegistrationHelper- Tells if Refitter should generate Apizr registration helpers (extended with dependencyInjectionSettings set, otherwise static)withCacheProvider- Set the cache provider to be usedwithPriority- Tells if Apizr should handle request prioritywithMediation- 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 usedwithFileTransfer- Tells if Apizr should handle file transfer
codeGeneratorSettings- Setting this allows customization of the NSwag generated types and contractsrequiredPropertiesMustBeDefined- Default is true,generateDataAnnotations- Default is true,anyType- Default isobject,dateType- Default isSystem.DateTimeOffset,dateTimeType- Default isSystem.DateTimeOffset,timeType- Default isSystem.TimeSpan,timeSpanType- Default isSystem.TimeSpan,arrayType- Default isSystem.Collections.Generic.ICollection,dictionaryType- Default isSystem.Collections.Generic.IDictionary,arrayInstanceType- Default isSystem.Collections.ObjectModel.Collection,dictionaryInstanceType- Default isSystem.Collections.Generic.Dictionary,arrayBaseType- Default isSystem.Collections.ObjectModel.Collection,dictionaryBaseType- Default isSystem.Collections.Generic.Dictionary,integerType- Default isInt32. The .NET type to use for OpenAPI integer types without a format specifier. Possible values:Int32,Int64propertySetterAccessModifier- 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 falsegenerateDefaultValues- Default is trueinlineNamedAny- Default is falseinlineJsonConverters- Default is true. When set to false, enum properties will not have[JsonConverter(typeof(JsonStringEnumConverter))]attributesdateFormat- Default is nulldateTimeFormat- Default is nullexcludedTypeNames- Default is emptycustomTemplateDirectory- 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
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.4.0-preview.125 | 48 | 11/14/2026 |
| 2.4.0-preview.124 | 43 | 11/10/2026 |
| 2.3.2-preview.123 | 53 | 11/5/2026 |
| 2.3.2-preview.122 | 105 | 10/26/2026 |
| 2.3.1 | 3,213 | 10/17/2026 |
| 2.3.1-preview.121 | 86 | 10/16/2026 |
| 2.3.1-preview.120 | 79 | 10/11/2026 |
| 2.3.1-preview.119 | 73 | 10/6/2026 |
| 2.3.1-preview.118 | 72 | 9/29/2026 |
| 2.3.0 | 3,418 | 9/28/2026 |
| 2.3.0-preview.117 | 76 | 9/28/2026 |
| 2.2.1 | 2,678 | 9/19/2026 |
| 2.2.1-preview.116 | 91 | 9/19/2026 |
| 2.2.0 | 1,372 | 9/7/2026 |
| 2.2.0-preview.115 | 95 | 9/6/2026 |
| 2.1.3 | 9,508 | 8/2/2026 |
| 2.1.2 | 2,222 | 7/28/2026 |
| 2.1.2-preview.114 | 84 | 7/28/2026 |
| 2.1.2-preview.113 | 87 | 7/28/2026 |
| 2.1.1 | 254 | 7/27/2026 |