Skip to content

Refit API reference

Find Refit types, overloads, parameters, and return values in one place. The tables are grouped by category and topic. Follow a topic link for its walkthrough, examples, and detailed behavior. Use your browser's find command to look up a type or method name.

Clients and settings

Create a client

Full description and examples.

Types: Refit.RestService.

Creation overloads

Full description and examples.

OverloadDescriptionParametersReturns
RestServiceStatic factory class for creating Refit interface implementations.None.
CreateHttpClient(string hostUrl, RefitSettings? settings)Creates an HTTP client, chooses the configured handler chain, and sets its base address.string hostUrl: non-null, non-whitespace base address; RefitSettings settings: nullable settings for handlers and URL resolution.HttpClient with the configured base address; the caller owns it.
ForGenerated<T>(HttpClient client)Resolves the registered generated implementation for T with default settings and never builds reflected requests.HttpClient client: non-null client used by the implementation.T: generated implementation; if T inherits IDisposable, disposing it also disposes client. Throws InvalidOperationException when no generated implementation is available on modern .NET.
ForGenerated<T>(HttpClient client, RefitSettings settings)Resolves the registered generated implementation for T with the supplied settings and never builds reflected requests.HttpClient client: non-null client; RefitSettings settings: non-null serializer and request settings.T: generated implementation; if T inherits IDisposable, disposing it also disposes client. Throws InvalidOperationException when no generated implementation is available on modern .NET.
ForGenerated<T>(string hostUrl)Creates an HTTP client with default settings, then resolves the generated implementation for T.string hostUrl: non-null, non-whitespace base address for the created client.T: generated implementation; if T inherits IDisposable, disposing it also disposes the created client.
ForGenerated<T>(string hostUrl, RefitSettings settings)Creates an HTTP client with the supplied settings, then resolves the generated implementation for T.string hostUrl: non-null, non-whitespace base address; RefitSettings settings: non-null serializer and request settings.T: generated implementation; if T inherits IDisposable, disposing it also disposes the created client.
ForGenerated(Type refitInterfaceType, HttpClient client, RefitSettings settings)Resolves a generated implementation for the runtime interface type over the supplied client.Type refitInterfaceType: non-null Refit interface; HttpClient client: non-null transport; RefitSettings settings: non-null settings.object implementing the interface. For a source-generated disposable interface, disposing the cast implementation also disposes client. Throws InvalidOperationException when no generated implementation is available on modern .NET.
ForGenerated(Type refitInterfaceType, string hostUrl, RefitSettings settings)Creates an HTTP client with the supplied settings, then resolves the generated implementation for the runtime interface type.Type refitInterfaceType: non-null Refit interface; string hostUrl: non-null, non-whitespace base address; RefitSettings settings: non-null settings.object implementing the interface. For a source-generated disposable interface, disposing the cast implementation also disposes the created client.
For<T>(HttpClient client)Creates T over a shared client with default settings, using an inline generated implementation when registered and otherwise a reflected request builder.HttpClient client: transport used for requests.T: implementation for T; reflection can build requests when no inline generated implementation is registered. A source-generated T that inherits IDisposable disposes client when disposed.
For<T>(HttpClient client, RefitSettings? settings)Creates T over a shared client, preferring an inline generated implementation and otherwise creating a reflected request builder.HttpClient client: transport; RefitSettings settings: nullable settings, where null selects defaults.T: implementation for T; the reflected path uses the supplied settings. A source-generated T that inherits IDisposable disposes client when disposed.
For<T>(HttpClient client, IRequestBuilder<T> builder)Creates T over a shared client with the request builder you supply.HttpClient client: transport; IRequestBuilder<T> builder: request builder for T.T: implementation using the supplied request builder. A source-generated T that inherits IDisposable disposes client when disposed.
For<T>(string hostUrl)Creates an HTTP client with default settings, then creates T, using generated inline requests when available and reflection otherwise.string hostUrl: non-null, non-whitespace base address for the created client.T: implementation for T; if T inherits IDisposable, disposing it also disposes the created client.
For<T>(string hostUrl, RefitSettings? settings)Creates an HTTP client with the selected settings, then creates T, using generated inline requests when available and reflection otherwise.string hostUrl: non-null, non-whitespace base address; RefitSettings settings: nullable settings, where null selects defaults.T: implementation for T; if T inherits IDisposable, disposing it also disposes the created client.
For(Type refitInterfaceType, HttpClient client)Creates the runtime-selected interface over a shared client with default settings, using generated inline requests when available and reflection otherwise.Type refitInterfaceType: interface to implement; HttpClient client: transport.object implementing refitInterfaceType, using default settings. A source-generated disposable interface disposes client when its cast implementation is disposed.
For(Type refitInterfaceType, HttpClient client, RefitSettings? settings)Creates the runtime-selected interface over a shared client, preferring generated inline requests and otherwise creating a reflected request builder.Type refitInterfaceType: interface to implement; HttpClient client: transport; RefitSettings settings: nullable settings, where null selects defaults.object implementing refitInterfaceType; the reflected path uses the selected settings. A source-generated disposable interface disposes client when its cast implementation is disposed.
For(Type refitInterfaceType, HttpClient client, IRequestBuilder builder)Creates the runtime-selected interface with the non-generic request builder you supply.Type refitInterfaceType: interface to implement; HttpClient client: transport; IRequestBuilder builder: request builder to use.object implementing refitInterfaceType, using the supplied builder. A source-generated disposable interface disposes client when its cast implementation is disposed.
For(Type refitInterfaceType, string hostUrl)Creates an HTTP client with default settings, then creates the runtime-selected interface, using generated inline requests when available and reflection otherwise.Type refitInterfaceType: interface to implement; string hostUrl: non-null, non-whitespace base address for the created client.object implementing refitInterfaceType, using default settings; if that interface inherits IDisposable, disposing the cast implementation also disposes the created client.
For(Type refitInterfaceType, string hostUrl, RefitSettings? settings)Creates an HTTP client with the selected settings, then creates the runtime-selected interface, using generated inline requests when available and reflection otherwise.Type refitInterfaceType: interface to implement; string hostUrl: non-null, non-whitespace base address; RefitSettings settings: nullable settings, where null selects defaults.object implementing refitInterfaceType; if that interface inherits IDisposable, disposing the cast implementation also disposes the created client.

Dependency injection

Full description and examples.

Types: Refit.HttpClientFactoryExtensions, Refit.ISettingsFor, Refit.SettingsFor<T>.

Registration overloads

Full description and examples.

DeclarationDescriptionParameters and defaultsReturn/value type
IServiceCollection.AddRefitClient(Type refitInterfaceType)Registers the reflection request builder for refitInterfaceType using the default settings and Refit’s derived HTTP client name, then returns the builder for further HTTP configuration.IServiceCollection receiver; Type refitInterfaceType: Refit interface.IHttpClientBuilder: registers a reflection-capable client with default settings.
IServiceCollection.AddRefitClient(Type refitInterfaceType, RefitSettings? settings)Registers the reflection request builder for refitInterfaceType using the supplied fixed settings reference and Refit’s derived HTTP client name, then returns the builder for further HTTP configuration.refitInterfaceType; RefitSettings settings: nullable fixed settings.IHttpClientBuilder: registers a reflection-capable client using those settings.
IServiceCollection.AddRefitClient(Type refitInterfaceType, RefitSettings? settings, string? httpClientName)Registers the reflection request builder for refitInterfaceType using the supplied fixed settings reference and the supplied HTTP client name, then returns the builder for further HTTP configuration.refitInterfaceType; settings; string httpClientName: nullable underlying client name.IHttpClientBuilder: registers a reflection-capable client with fixed settings under that HTTP client name.
IServiceCollection.AddRefitClient(Type refitInterfaceType, Func<IServiceProvider, RefitSettings?>? settingsAction)Registers the reflection request builder for refitInterfaceType using the settings returned by settingsAction through DI and Refit’s derived HTTP client name, then returns the builder for further HTTP configuration.refitInterfaceType; Func<IServiceProvider, RefitSettings?> settingsAction: nullable provider settings factory.IHttpClientBuilder: registers a reflection-capable client whose settings come from DI.
IServiceCollection.AddRefitClient(Type refitInterfaceType, Func<IServiceProvider, RefitSettings?>? settingsAction, string? httpClientName)Registers the reflection request builder for refitInterfaceType using the settings returned by settingsAction through DI and the supplied HTTP client name, then returns the builder for further HTTP configuration.refitInterfaceType; settingsAction; httpClientName.IHttpClientBuilder: registers a reflection-capable client with DI-provided settings under that HTTP client name.
IServiceCollection.AddRefitClient<T>()Registers the reflection request builder for T using the default settings and Refit’s derived HTTP client name, then returns the builder for further HTTP configuration.None; T : class is the Refit interface.IHttpClientBuilder: registers reflection-capable T with default settings.
IServiceCollection.AddRefitClient<T>(RefitSettings? settings)Registers the reflection request builder for T using the supplied fixed settings reference and Refit’s derived HTTP client name, then returns the builder for further HTTP configuration.T : class; settings: nullable fixed settings.IHttpClientBuilder: registers reflection-capable T using those settings.
IServiceCollection.AddRefitClient<T>(RefitSettings? settings, string? httpClientName)Registers the reflection request builder for T using the supplied fixed settings reference and the supplied HTTP client name, then returns the builder for further HTTP configuration.T : class; settings; httpClientName.IHttpClientBuilder: registers reflection-capable T with fixed settings under that HTTP client name.
IServiceCollection.AddRefitClient<T>(Func<IServiceProvider, RefitSettings?>? settingsAction)Registers the reflection request builder for T using the settings returned by settingsAction through DI and Refit’s derived HTTP client name, then returns the builder for further HTTP configuration.T : class; settingsAction: nullable provider settings factory.IHttpClientBuilder: registers reflection-capable T with settings resolved from DI.
IServiceCollection.AddRefitClient<T>(Func<IServiceProvider, RefitSettings?>? settingsAction, string? httpClientName)Registers the reflection request builder for T using the settings returned by settingsAction through DI and the supplied HTTP client name, then returns the builder for further HTTP configuration.T : class; settingsAction; httpClientName.IHttpClientBuilder: registers reflection-capable T with DI-provided settings under that HTTP client name.
IServiceCollection.AddKeyedRefitClient(Type refitInterfaceType, object? serviceKey)Registers the reflection request builder for refitInterfaceType under the required non-null service key using the default settings and Refit’s derived HTTP client name, then returns the builder for further HTTP configuration.refitInterfaceType; object serviceKey: non-null DI key.IHttpClientBuilder: registers a keyed reflection-capable client with default settings.
IServiceCollection.AddKeyedRefitClient(Type refitInterfaceType, object? serviceKey, RefitSettings? settings)Registers the reflection request builder for refitInterfaceType under the required non-null service key using the supplied fixed settings reference and Refit’s derived HTTP client name, then returns the builder for further HTTP configuration.refitInterfaceType; serviceKey; settings: nullable fixed settings.IHttpClientBuilder: registers a keyed reflection-capable client using those settings.
IServiceCollection.AddKeyedRefitClient(Type refitInterfaceType, object? serviceKey, RefitSettings? settings, string? httpClientName)Registers the reflection request builder for refitInterfaceType under the required non-null service key using the supplied fixed settings reference and the supplied HTTP client name, then returns the builder for further HTTP configuration.refitInterfaceType; serviceKey; settings; httpClientName.IHttpClientBuilder: registers a keyed reflection-capable client with fixed settings under that HTTP client name.
IServiceCollection.AddKeyedRefitClient(Type refitInterfaceType, object? serviceKey, Func<IServiceProvider, RefitSettings?>? settingsAction)Registers the reflection request builder for refitInterfaceType under the required non-null service key using the settings returned by settingsAction through DI and Refit’s derived HTTP client name, then returns the builder for further HTTP configuration.refitInterfaceType; serviceKey; settingsAction: nullable provider settings factory.IHttpClientBuilder: registers a keyed reflection-capable client with settings resolved from DI.
IServiceCollection.AddKeyedRefitClient(Type refitInterfaceType, object? serviceKey, Func<IServiceProvider, RefitSettings?>? settingsAction, string? httpClientName)Registers the reflection request builder for refitInterfaceType under the required non-null service key using the settings returned by settingsAction through DI and the supplied HTTP client name, then returns the builder for further HTTP configuration.refitInterfaceType; serviceKey; settingsAction; httpClientName.IHttpClientBuilder: registers a keyed reflection-capable client with DI-provided settings under that HTTP client name.
IServiceCollection.AddKeyedRefitClient<T>(object? serviceKey)Registers the reflection request builder for T under the required non-null service key using the default settings and Refit’s derived HTTP client name, then returns the builder for further HTTP configuration.T : class; serviceKey: non-null DI key.IHttpClientBuilder: registers keyed reflection-capable T with default settings.
IServiceCollection.AddKeyedRefitClient<T>(object? serviceKey, RefitSettings? settings)Registers the reflection request builder for T under the required non-null service key using the supplied fixed settings reference and Refit’s derived HTTP client name, then returns the builder for further HTTP configuration.T : class; serviceKey; settings: nullable fixed settings.IHttpClientBuilder: registers keyed reflection-capable T using those settings.
IServiceCollection.AddKeyedRefitClient<T>(object? serviceKey, RefitSettings? settings, string? httpClientName)Registers the reflection request builder for T under the required non-null service key using the supplied fixed settings reference and the supplied HTTP client name, then returns the builder for further HTTP configuration.T : class; serviceKey; settings; httpClientName.IHttpClientBuilder: registers keyed reflection-capable T with fixed settings under that HTTP client name.
IServiceCollection.AddKeyedRefitClient<T>(object? serviceKey, Func<IServiceProvider, RefitSettings?>? settingsAction)Registers the reflection request builder for T under the required non-null service key using the settings returned by settingsAction through DI and Refit’s derived HTTP client name, then returns the builder for further HTTP configuration.T : class; serviceKey; settingsAction: nullable provider settings factory.IHttpClientBuilder: registers keyed reflection-capable T with settings resolved from DI.
IServiceCollection.AddKeyedRefitClient<T>(object? serviceKey, Func<IServiceProvider, RefitSettings?>? settingsAction, string? httpClientName)Registers the reflection request builder for T under the required non-null service key using the settings returned by settingsAction through DI and the supplied HTTP client name, then returns the builder for further HTTP configuration.T : class; serviceKey; settingsAction; httpClientName.IHttpClientBuilder: registers keyed reflection-capable T with DI-provided settings under that HTTP client name.
IServiceCollection.AddRefitGeneratedClient<T>()Registers the generated implementation of T using the default settings and Refit’s derived HTTP client name, then returns the builder for further HTTP configuration.None; T : class is the generated Refit interface.IHttpClientBuilder: registers the generated-only implementation of T with default settings.
IServiceCollection.AddRefitGeneratedClient<T>(RefitSettings? settings)Registers the generated implementation of T using the supplied fixed settings reference and Refit’s derived HTTP client name, then returns the builder for further HTTP configuration.T : class; settings: nullable fixed settings.IHttpClientBuilder: registers generated-only T using those settings.
IServiceCollection.AddRefitGeneratedClient<T>(RefitSettings? settings, string? httpClientName)Registers the generated implementation of T using the supplied fixed settings reference and the supplied HTTP client name, then returns the builder for further HTTP configuration.T : class; settings; httpClientName.IHttpClientBuilder: registers generated-only T with fixed settings under that HTTP client name.
IServiceCollection.AddRefitGeneratedClient<T>(Func<IServiceProvider, RefitSettings?>? settingsAction)Registers the generated implementation of T using the settings returned by settingsAction through DI and Refit’s derived HTTP client name, then returns the builder for further HTTP configuration.T : class; settingsAction: nullable provider settings factory.IHttpClientBuilder: registers generated-only T with settings resolved from DI.
IServiceCollection.AddRefitGeneratedClient<T>(Func<IServiceProvider, RefitSettings?>? settingsAction, string? httpClientName)Registers the generated implementation of T using the settings returned by settingsAction through DI and the supplied HTTP client name, then returns the builder for further HTTP configuration.T : class; settingsAction; httpClientName.IHttpClientBuilder: registers generated-only T with DI-provided settings under that HTTP client name.
IServiceCollection.AddKeyedRefitGeneratedClient<T>(object? serviceKey)Registers the generated implementation of T under the required non-null service key using the default settings and Refit’s derived HTTP client name, then returns the builder for further HTTP configuration.T : class; serviceKey: non-null DI key.IHttpClientBuilder: registers keyed generated-only T with default settings.
IServiceCollection.AddKeyedRefitGeneratedClient<T>(object? serviceKey, RefitSettings? settings)Registers the generated implementation of T under the required non-null service key using the supplied fixed settings reference and Refit’s derived HTTP client name, then returns the builder for further HTTP configuration.T : class; serviceKey; settings: nullable fixed settings.IHttpClientBuilder: registers keyed generated-only T using those settings.
IServiceCollection.AddKeyedRefitGeneratedClient<T>(object? serviceKey, RefitSettings? settings, string? httpClientName)Registers the generated implementation of T under the required non-null service key using the supplied fixed settings reference and the supplied HTTP client name, then returns the builder for further HTTP configuration.T : class; serviceKey; settings; httpClientName.IHttpClientBuilder: registers keyed generated-only T with fixed settings under that HTTP client name.
IServiceCollection.AddKeyedRefitGeneratedClient<T>(object? serviceKey, Func<IServiceProvider, RefitSettings?>? settingsAction)Registers the generated implementation of T under the required non-null service key using the settings returned by settingsAction through DI and Refit’s derived HTTP client name, then returns the builder for further HTTP configuration.T : class; serviceKey; settingsAction: nullable provider settings factory.IHttpClientBuilder: registers keyed generated-only T with settings resolved from DI.
IServiceCollection.AddKeyedRefitGeneratedClient<T>(object? serviceKey, Func<IServiceProvider, RefitSettings?>? settingsAction, string? httpClientName)Registers the generated implementation of T under the required non-null service key using the settings returned by settingsAction through DI and the supplied HTTP client name, then returns the builder for further HTTP configuration.T : class; serviceKey; settingsAction; httpClientName.IHttpClientBuilder: registers keyed generated-only T with DI-provided settings under that HTTP client name.
IHttpClientBuilder.AddRefitClient(Type refitInterfaceType)Registers the reflection request builder for refitInterfaceType using the default settings and the existing builder name, then returns the builder for further HTTP configuration.IHttpClientBuilder receiver; refitInterfaceType; preserves the builder name.IHttpClientBuilder: adds a reflection-capable client to the existing named builder with default settings.
IHttpClientBuilder.AddRefitClient(Type refitInterfaceType, RefitSettings? settings)Registers the reflection request builder for refitInterfaceType using the supplied fixed settings reference and the existing builder name, then returns the builder for further HTTP configuration.refitInterfaceType; settings: nullable fixed settings.IHttpClientBuilder: adds a reflection-capable client to the existing builder using those settings.
IHttpClientBuilder.AddRefitClient(Type refitInterfaceType, Func<IServiceProvider, RefitSettings?>? settingsAction)Registers the reflection request builder for refitInterfaceType using the settings returned by settingsAction through DI and the existing builder name, then returns the builder for further HTTP configuration.refitInterfaceType; settingsAction: nullable provider settings factory.IHttpClientBuilder: adds a reflection-capable client to the existing builder with DI-provided settings.
IHttpClientBuilder.AddRefitClient<T>()Registers the reflection request builder for T using the default settings and the existing builder name, then returns the builder for further HTTP configuration.None; T : class is the Refit interface.IHttpClientBuilder: adds reflection-capable T to the existing named builder with default settings.
IHttpClientBuilder.AddRefitClient<T>(RefitSettings? settings)Registers the reflection request builder for T using the supplied fixed settings reference and the existing builder name, then returns the builder for further HTTP configuration.T : class; settings: nullable fixed settings.IHttpClientBuilder: adds reflection-capable T to the existing builder using those settings.
IHttpClientBuilder.AddRefitClient<T>(Func<IServiceProvider, RefitSettings?>? settingsAction)Registers the reflection request builder for T using the settings returned by settingsAction through DI and the existing builder name, then returns the builder for further HTTP configuration.T : class; settingsAction: nullable provider settings factory.IHttpClientBuilder: adds reflection-capable T to the existing builder with DI-provided settings.
IHttpClientBuilder.AddKeyedRefitClient(Type refitInterfaceType, object? serviceKey)Registers the reflection request builder for refitInterfaceType under the required non-null service key using the default settings and the existing builder name, then returns the builder for further HTTP configuration.refitInterfaceType; serviceKey: non-null DI key.IHttpClientBuilder: adds a keyed reflection-capable client to the existing named builder with default settings.
IHttpClientBuilder.AddKeyedRefitClient(Type refitInterfaceType, object? serviceKey, RefitSettings? settings)Registers the reflection request builder for refitInterfaceType under the required non-null service key using the supplied fixed settings reference and the existing builder name, then returns the builder for further HTTP configuration.refitInterfaceType; serviceKey; settings: nullable fixed settings.IHttpClientBuilder: adds a keyed reflection-capable client to the existing builder using those settings.
IHttpClientBuilder.AddKeyedRefitClient(Type refitInterfaceType, object? serviceKey, Func<IServiceProvider, RefitSettings?>? settingsAction)Registers the reflection request builder for refitInterfaceType under the required non-null service key using the settings returned by settingsAction through DI and the existing builder name, then returns the builder for further HTTP configuration.refitInterfaceType; serviceKey; settingsAction: nullable provider settings factory.IHttpClientBuilder: adds a keyed reflection-capable client to the existing builder with DI-provided settings.
IHttpClientBuilder.AddKeyedRefitClient<T>(object? serviceKey)Registers the reflection request builder for T under the required non-null service key using the default settings and the existing builder name, then returns the builder for further HTTP configuration.T : class; serviceKey: non-null DI key.IHttpClientBuilder: adds keyed reflection-capable T to the existing named builder with default settings.
IHttpClientBuilder.AddKeyedRefitClient<T>(object? serviceKey, RefitSettings? settings)Registers the reflection request builder for T under the required non-null service key using the supplied fixed settings reference and the existing builder name, then returns the builder for further HTTP configuration.T : class; serviceKey; settings: nullable fixed settings.IHttpClientBuilder: adds keyed reflection-capable T to the existing builder using those settings.
IHttpClientBuilder.AddKeyedRefitClient<T>(object? serviceKey, Func<IServiceProvider, RefitSettings?>? settingsAction)Registers the reflection request builder for T under the required non-null service key using the settings returned by settingsAction through DI and the existing builder name, then returns the builder for further HTTP configuration.T : class; serviceKey; settingsAction: nullable provider settings factory.IHttpClientBuilder: adds keyed reflection-capable T to the existing builder with DI-provided settings.
IHttpClientBuilder.AddAuthorizationHeaderValueProvider(Func<IServiceProvider, HttpRequestMessage, CancellationToken, ValueTask<string>> getToken)Adds a handler to this builder that creates a fresh DI scope for each request and calls getToken with that scope, request and cancellation token.IHttpClientBuilder receiver; Func<IServiceProvider, HttpRequestMessage, CancellationToken, ValueTask<string>> getToken: per-request token callback.IHttpClientBuilder: attaches a handler that resolves the authorization token in a fresh DI scope for each request.
SettingsFor<T>(RefitSettings? settings)Constructs a SettingsFor<T> holder that keeps the supplied nullable settings reference for interface type T.RefitSettings? settings: settings reference or null; T identifies the interface.New SettingsFor<T> holder that stores that settings reference for one registered interface.
SettingsFor<T>.SettingsExposes the nullable RefitSettings reference associated with the registered Refit interface.None.RefitSettings?: the settings reference stored for T; it can be null to select defaults.
ISettingsFor.SettingsExposes the nullable RefitSettings reference from a SettingsFor<T> instance without exposing its interface type.None.RefitSettings?: the settings reference stored by that holder.
TypePurpose
Refit.HttpClientFactoryExtensionsStatic extension class for service-collection and existing-builder registration methods.
Refit.ISettingsForInterface that exposes a nullable settings reference without a closed Refit interface type.
Refit.SettingsFor<T>Generic DI holder that associates a nullable settings reference with interface type T.

Settings

Full description and examples.

Types: Refit.RefitSettings.

Settings reference

Full description and examples.

MemberDescriptionParametersReturns or value
RefitSettingsHolds the serializer, URL/form formatters, request-building options, exception factories, and HTTP-version settings used by a Refit client.None.Mutable settings object.
RefitSettings()Creates a complete settings object with Refit's default serializer, formatters, and exception factories.None.New settings with the System.Text.Json serializer, default URL, form, and key formatters, plus default exception factories.
RefitSettings(IHttpContentSerializer contentSerializer)Creates settings that use the supplied content serializer and the other defaults.IHttpContentSerializer contentSerializer: serializer; must not be null.New settings using the supplied serializer and default URL, form, and key formatters.
RefitSettings(IHttpContentSerializer contentSerializer, IUrlParameterFormatter? urlParameterFormatter)Creates settings with a supplied serializer and URL-value formatter.IHttpContentSerializer contentSerializer: required serializer; IUrlParameterFormatter urlParameterFormatter: formatter or null for the default.New settings using the supplied choices and the default form and key formatters.
RefitSettings(IHttpContentSerializer contentSerializer, IUrlParameterFormatter? urlParameterFormatter, IFormUrlEncodedParameterFormatter? formUrlEncodedParameterFormatter)Creates settings with supplied serializer, URL-value, and form-value formatters.IHttpContentSerializer contentSerializer: required serializer; IUrlParameterFormatter urlParameterFormatter: formatter or null; IFormUrlEncodedParameterFormatter formUrlEncodedParameterFormatter: formatter or null.New settings using the supplied choices and the default key formatter.
RefitSettings(IHttpContentSerializer contentSerializer, IUrlParameterFormatter? urlParameterFormatter, IFormUrlEncodedParameterFormatter? formUrlEncodedParameterFormatter, IUrlParameterKeyFormatter? urlParameterKeyFormatter)Creates settings with supplied serializer and all formatter choices.IHttpContentSerializer contentSerializer: required serializer; IUrlParameterFormatter urlParameterFormatter: formatter or null; IFormUrlEncodedParameterFormatter formUrlEncodedParameterFormatter: formatter or null; IUrlParameterKeyFormatter urlParameterKeyFormatter: formatter or null.New settings; a null formatter selects its default.
RefitSettings.CamelCase()Creates settings that serialize JSON and format URL/form keys in camelCase.None.New RefitSettings using camelCase JSON and URL/form keys.
RefitSettings.SnakeCase()Creates settings that serialize JSON and format URL/form keys in snake_case.None.New RefitSettings using snake_case JSON and URL/form keys.
RefitSettings.KebabCase()Creates settings that serialize JSON and format URL/form keys in kebab-case.None.New RefitSettings using kebab-case JSON and URL/form keys.
AuthorizationHeaderValueGetterSupplies a token for a declared [Authorize] header that has no token. Generated preparation uses it even with a supplied HttpClient; a settings-created handler also uses it for an explicit token.Func<HttpRequestMessage, CancellationToken, ValueTask<string>> or null.Token getter; default null. An empty returned token removes the header.
HttpMessageHandlerFactorySupplies the primary handler when Refit creates the HttpClient.Func<HttpMessageHandler> or null.Handler factory; default null. Refit ignores it when you supply an existing HttpClient.
ExceptionFactoryMaps unsuccessful HTTP responses to exceptions.Func<HttpResponseMessage, ValueTask<Exception?>>.Exception factory; default creates Refit API exceptions. A null result suppresses the HTTP error.
DeserializationExceptionFactoryMaps response-body deserialization failures to exceptions.Func<HttpResponseMessage, Exception, ValueTask<Exception?>> or null.Deserialization exception factory; default null. A null result suppresses the error.
ContentSerializerSerializes request bodies and deserializes response bodies.IHttpContentSerializer.Body/reply serializer; default SystemTextJsonContentSerializer.
ReturnTypeAdaptersRegisters custom return wrappers for the opt-in reflection request builder, such as IObservable<T>.Read-only IList<Type> property.Mutable adapter list; default empty. Reflection builds consult it; source-generated builds discover adapters at compile time.
UrlParameterKeyFormatterFormats parameter names used in route, query, and form data.IUrlParameterKeyFormatter.URL/form key formatter; default DefaultUrlParameterKeyFormatter.
HonorContentSerializerPropertyNamesInQueryChooses whether flattened query names follow serializer property names.bool.true makes flattened query keys honor serializer names; default true. AliasAs wins in either mode.
UrlParameterFormatterFormats parameter values inserted into URLs.IUrlParameterFormatter.Path/query value formatter; default DefaultUrlParameterFormatter.
UrlParameterFormatterMapSelects URL value formatters by exact runtime type before the general formatter.Read-only IDictionary<Type, IUrlParameterFormatter> property.Mutable formatter map; default empty. Base classes and interfaces are not searched.
FormUrlEncodedParameterFormatterFormats values written into form-url-encoded request bodies.IFormUrlEncodedParameterFormatter.Form value formatter; default DefaultFormUrlEncodedParameterFormatter.
CollectionFormatSelects how collection values become repeated or joined URL parameters.CollectionFormat.Collection rendering mode; default RefitParameterFormatter.
BufferedChooses whether request content is buffered before the HTTP send.bool.Buffer request content before sending; default false.
CaptureRequestContentCaptures request-body text so an ApiExceptionBase can expose it after a failed request.bool.Retain request-body text in memory; default false. Avoid it for large or streamed uploads.
CaptureMethodArgumentsStores boxed interface-call arguments in the request options for a handler to inspect.bool.Retain an object?[] for the request lifetime; default false.
MaxExceptionContentLengthLimits the response-body characters captured while building an API exception.int? characters.Error-body capture limit; default null (unbounded).
ExceptionRedactorScrubs sensitive data from an ApiExceptionBase before Refit returns it.Action<ApiExceptionBase> or null.Exception scrubbing hook; default null.
AllowUnmatchedRouteParametersAllows route placeholders without matching method parameters.bool.Leaves unmatched {token} text for later rewriting when true; default false.
ValidateHeadersEnables framework validation when Refit applies declared headers.bool.Use framework header parsing; default false. Invalid values throw FormatException when a request is built.
UrlResolutionSelects how relative request paths resolve against HttpClient.BaseAddress.UrlResolutionMode.Base-address resolution mode; default RefitLegacy.
RequestBodySerializationSelects how Refit creates JSON request-body content.RequestBodySerializationMode.JSON body serialization mode; default Default. Buffered and Streamed require ISynchronousContentSerializer.
RequestCompressionSelects the content encoding applied to every request body.RequestCompression.Request-body coding; default None. A [Body] coding overrides this setting.
RequestCompressionLevelSets the compression effort for compressed request bodies.CompressionLevel.Compression effort; default Optimal.
RequestCompressionOptionsProvides per-coding compressor settings that override the compression level for that coding.RequestCompressionOptions or null (.NET 9+).Per-coding compressor settings; default null, which uses the compression level.
HttpRequestMessageOptionsCopies these local values to every generated request's options on modern .NET, or properties on .NET Framework.Dictionary<string, object> or null; init only.Local request values; default null. The dictionary remains mutable after initialization.
TransportExceptionFactoryMaps exceptions thrown by HttpClient.SendAsync to the exception Refit surfaces.Func<HttpRequestMessage, Exception, CancellationToken, Exception>.Default preserves an OperationCanceledException when its token was cancelled; otherwise it wraps the failure in ApiRequestException.
VersionSets the HTTP version requested on generated requests.Version (.NET 6+).Requested HTTP version; default HTTP/1.1.
VersionPolicySets the policy used when negotiating the requested HTTP version.HttpVersionPolicy (.NET 6+).Version negotiation policy; default RequestVersionOrLower.
EnumValueMeaning
CollectionFormatRefitParameterFormatter (0)Use the configured value formatter.
CollectionFormatCsv (1), Ssv (2), Tsv (3), Pipes (4)Comma, space, tab, or pipe separated values.
CollectionFormatMulti (5)Repeat the parameter for each value.
CollectionFormatIndexed (6)Expand object elements with indexed keys.
RequestBodySerializationModeDefault (0)Normal asynchronous serialization.
RequestBodySerializationModeBuffered (1)Synchronous serialization into buffered content.
RequestBodySerializationModeStreamed (2)Synchronous serialization to the request stream.
RequestCompressionDefault (0), None (1), GZip (2), Brotli (3), Zstandard (4)Use settings, no coding, gzip, Brotli, or Zstandard. Brotli requires .NET 8; Zstandard requires .NET 11.
CompressionLevelOptimal (0), Fastest (1), NoCompression (2), SmallestSize (3)Compression effort choices used by RequestCompressionLevel.
UrlResolutionModeRefitLegacy (0), Rfc3986 (1)Legacy base-path prepending or RFC 3986 URI resolution.
System.Net.Http.HttpVersionPolicyRequestVersionOrLower (0), RequestVersionOrHigher (1), RequestVersionExact (2)HTTP version negotiation choices.

Request builders

Full description and examples.

Types: Refit.IRequestBuilder, Refit.IRequestBuilder<T>, Refit.RequestBuilder.

Close a generic method

Full description and examples.

DeclarationDescriptionParameters and defaultsReturn/value
RequestBuilder.ForType<T>(RefitSettings? settings)Resolves the optional reflection factory and creates a strongly typed builder for T; null settings are passed through to the factory.RefitSettings settings: settings for request construction, or null. T is the Refit API interface.IRequestBuilder<T> for T.
RequestBuilder.ForType<T>()Resolves the optional reflection factory and creates a strongly typed builder for T with null settings.T is the Refit API interface.IRequestBuilder<T> for T.
RequestBuilder.ForType(Type refitInterfaceType, RefitSettings? settings)Resolves the optional reflection factory and creates a builder for the supplied Refit interface type.Type refitInterfaceType: Refit interface, including a closed generic interface. RefitSettings settings: settings for request construction, or null.IRequestBuilder for refitInterfaceType.
RequestBuilder.ForType(Type refitInterfaceType)Calls the settings overload with null and creates a builder for the supplied Refit interface type.Type refitInterfaceType: Refit interface, including a closed generic interface.IRequestBuilder for refitInterfaceType.
IRequestBuilder.SettingsExposes the RefitSettings instance used by this builder.None.RefitSettings used by the builder.
IRequestBuilder.BuildRestResultFuncForMethod(string methodName, Type[]? parameterTypes = null, Type[]? genericArgumentTypes = null)Resolves and caches a delegate for a reflected interface method. The delegate builds the request and follows the method's declared return shape when invoked.string methodName: interface method name. Type[] parameterTypes: declaration-order parameter types, default null; required to select among overloads. Type[] genericArgumentTypes: types used to close a generic method, default null.Func<HttpClient, object[], object?>, taking an HttpClient and argument array and returning the method's declared result.
RestService.RegisterGeneratedFactory(Type refitInterfaceType, Func<HttpClient, IRequestBuilder, object> factory)Stores a source-generated factory under an interface Type; a later registration for the same type replaces it.Type refitInterfaceType: interface key. Func<HttpClient, IRequestBuilder, object> factory: receives the client and a generated-only IRequestBuilder.void; stores the factory. Null type or factory throws ArgumentNullException.
RestService.RegisterGeneratedFactory<T>(Func<HttpClient, IRequestBuilder, T> factory)Stores a typed source-generated factory under typeof(T).Func<HttpClient, IRequestBuilder, T> factory: receives the client and generated-only builder and returns T. T is the Refit interface.void; stores the typed factory. A null factory throws ArgumentNullException.
RestService.RegisterGeneratedSettingsFactory<T>(Func<HttpClient, RefitSettings, T> factory)Stores a typed source-generated factory that receives settings directly, so generated clients can build requests inline without reflection.Func<HttpClient, RefitSettings, T> factory: receives the client and settings and returns T. T is the Refit interface.void; stores the settings factory. A null factory throws ArgumentNullException.
IRequestBuilderDefines the settings property and dynamic method-delegate operation used by request builders.None.Interface implemented by reflection and generated-only builders.
IRequestBuilder<T>Carries the target API interface type T while inheriting the untyped builder contract.T is the Refit API interface.IRequestBuilder.
RequestBuilderProvides static entry points that resolve the optional reflection request-builder factory.None.Static class.

Requests

Routes and HTTP methods

Full description and examples.

Types: Refit.DeleteAttribute, Refit.GetAttribute, Refit.HeadAttribute, Refit.HttpMethodAttribute, Refit.OptionsAttribute, Refit.PatchAttribute, Refit.PathPrefixAttribute, Refit.PostAttribute, Refit.PutAttribute, Refit.UrlAttribute.

Pick an HTTP method

Full description and examples.

AttributeHTTP methodCommon use
[Get(path)]GETRead a resource.
[Post(path)]POSTSubmit data or create a resource.
[Put(path)]PUTReplace a resource.
[Patch(path)]PATCHChange part of a resource.
[Delete(path)]DELETERemove a resource.
[Head(path)]HEADRead reply headers without a reply body.
[Options(path)]OPTIONSAsk what operations a service accepts.

Route attribute reference

Full description and examples.

MemberDescriptionParametersReturns or value
HttpMethodAttributeBase attribute for declaring the HTTP method and route template used by a Refit interface method.None. Abstract class.Attribute type inherited by Refit's built-in HTTP method attributes.
HttpMethodAttribute(string path)Stores the route template for an HTTP operation.string path: route template.Initializes the base attribute with the supplied path.
HttpMethodAttribute.MethodIdentifies the HTTP verb represented by the attribute.None. Abstract getter.HttpMethod for the operation.
HttpMethodAttribute.PathHolds the route template Refit combines with method parameters.None publicly; protected setter for derived attributes.string route template supplied to the constructor or changed by a subclass.
DeleteAttributeAttribute that declares a DELETE request on an interface method.None. Sealed attribute for methods.Attribute type inherited from HttpMethodAttribute.
DeleteAttribute(string path)Declares a DELETE route with the supplied template.string path: route template.Initializes a DELETE route attribute.
DeleteAttribute.MethodSupplies the HTTP method for a DELETE route.None.HttpMethod.Delete.
GetAttributeAttribute that declares a GET request on an interface method.None. Sealed attribute for methods.Attribute type inherited from HttpMethodAttribute.
GetAttribute(string path)Declares a GET route with the supplied template.string path: route template.Initializes a GET route attribute.
GetAttribute.MethodSupplies the HTTP method for a GET route.None.HttpMethod.Get.
HeadAttributeAttribute that declares a HEAD request on an interface method.None. Sealed attribute for methods.Attribute type inherited from HttpMethodAttribute.
HeadAttribute(string path)Declares a HEAD route with the supplied template.string path: route template.Initializes a HEAD route attribute.
HeadAttribute.MethodSupplies the HTTP method for a HEAD route.None.HttpMethod.Head.
OptionsAttributeAttribute that declares an OPTIONS request on an interface method.None. Sealed attribute for methods.Attribute type inherited from HttpMethodAttribute.
OptionsAttribute(string path)Declares an OPTIONS route with the supplied template.string path: route template.Initializes an OPTIONS route attribute.
OptionsAttribute.MethodSupplies the HTTP method for an OPTIONS route.None.HttpMethod whose method name is OPTIONS.
PatchAttributeAttribute that declares a PATCH request on an interface method.None. Sealed attribute for methods.Attribute type inherited from HttpMethodAttribute.
PatchAttribute(string path)Declares a PATCH route with the supplied template.string path: route template.Initializes a PATCH route attribute.
PatchAttribute.MethodSupplies a custom HttpMethod whose name is PATCH.None.HTTP method named PATCH.
PathPrefixAttributeAttribute that prepends a shared route prefix to methods on an interface.None. Sealed attribute for interfaces.Interface attribute carrying a shared route prefix.
PathPrefixAttribute(string prefix)Stores the prefix Refit applies to the interface's method routes.string prefix: shared route prefix.Initializes an interface route-prefix attribute.
PathPrefixAttribute.PrefixExposes the prefix supplied to the constructor.None. Read-only.string route prefix.
PostAttributeAttribute that declares a POST request on an interface method.None. Sealed attribute for methods.Attribute type inherited from HttpMethodAttribute.
PostAttribute(string path)Declares a POST route with the supplied template.string path: route template.Initializes a POST route attribute.
PostAttribute.MethodSupplies the HTTP method for a POST route.None.HttpMethod.Post.
PutAttributeAttribute that declares a PUT request on an interface method.None. Sealed attribute for methods.Attribute type inherited from HttpMethodAttribute.
PutAttribute(string path)Declares a PUT route with the supplied template.string path: route template.Initializes a PUT route attribute.
PutAttribute.MethodSupplies the HTTP method for a PUT route.None.HttpMethod.Put.
UrlAttributeAttribute that marks a parameter as the complete absolute request URL.None. Sealed attribute for parameters.Parameter marker consumed while Refit builds the request.
UrlAttribute()Marks a method parameter as the absolute URL used for the request.None.Initializes a URL parameter marker.

Query names, values and collections

Full description and examples.

Types: Refit.AliasAsAttribute, Refit.CollectionFormat, Refit.EncodedAttribute, Refit.QueryAttribute, Refit.QueryNameAttribute, Refit.QueryUriFormatAttribute.

Send a collection

Full description and examples.

CollectionFormatShape for two string values
Csvtags=math%2Ccode
Ssvtags=math%20code
Tsvtags=math%09code
Pipestags=math%7Ccode
Multitags=math&tags=code
IndexedObject properties such as people[0].Id=1&people[1].Id=2.
RefitParameterFormatterUses the configured formatter. The default query formatter joins values with commas.

Query attribute choices

Full description and examples.

Attribute or propertyUse
AliasAs(name) / NameSets an explicit parameter or property name.
Query()Keeps the default delimiter and the configured collection format.
Query(delimiter) / DelimiterChooses the text between nested names. The default is ..
Query(delimiter, prefix) / PrefixAdds a name before flattened properties.
Query(delimiter, prefix, format) / FormatAlso supplies a value format string.
Query(collectionFormat) / CollectionFormatSelects a collection format for this argument.
Query.IsCollectionFormatSpecifiedTells custom code whether the attribute explicitly chose a collection format.
Query.TreatAsStringUses the object's ToString() result instead of flattening its properties.
Query.SerializeNullSends a null property as an empty value.
QueryName()Sends valueless flags.
Encoded()Keeps caller-escaped text.
QueryUriFormat(uriFormat) / UriFormatSets the final path and query rendering mode.
MemberDescriptionParametersReturns or value
CollectionFormatSelects how a collection becomes query or form text.None.enum with the values listed above.
CollectionFormat.RefitParameterFormatterDelegates collection rendering to the configured URL or form formatter.None.int value 0; the default enum value.
CollectionFormat.CsvJoins values with a comma.None.int value 1.
CollectionFormat.SsvJoins values with a space.None.int value 2.
CollectionFormat.TsvJoins values with a tab.None.int value 3.
CollectionFormat.PipesJoins values with a pipe character.None.int value 4.
CollectionFormat.MultiEmits one key-value pair for each collection value.None.int value 5.
CollectionFormat.IndexedExpands each object element under an indexed key such as items[0].Name.None.int value 6; scalar elements use comma-separated values.
AliasAsAttributeAn attribute that replaces a query parameter or property name with a service-specific name.Applied to a parameter or property.Sealed Attribute type.
AliasAsAttribute(string name)Marks a parameter or property with the exact name Refit sends on the wire.string name: wire name.An attribute whose Name replaces the CLR name.
AliasAsAttribute.NameReturns the alias supplied to the constructor.None. Read-only.string wire name.
EncodedAttributeAn attribute that tells generated request building to preserve a caller-encoded parameter.Applied to a parameter.Sealed Attribute type.
EncodedAttribute()Marks a parameter value as URL-encoded text that Refit appends verbatim.None.Attribute for path segments, query values, and QueryName flags.
QueryAttributeAn attribute that controls query or form field names, scalar formats, and collection formats.Applied to a parameter or property.Sealed Attribute type.
QueryAttribute()Uses . as the nested-name delimiter and leaves the collection format to client settings.None.Attribute with no prefix or value format.
QueryAttribute(CollectionFormat collectionFormat)Selects a collection format for this parameter or property.CollectionFormat collectionFormat: explicit collection mode.Attribute for which IsCollectionFormatSpecified is true.
QueryAttribute(string delimiter)Changes the separator between names when Refit flattens a complex value.string delimiter: nested-name separator.Attribute with the supplied delimiter.
QueryAttribute(string delimiter, string prefix)Changes flattened names to prefix + delimiter + propertyName.string delimiter: nested-name separator; string prefix: name before flattened properties.Attribute with the supplied delimiter and prefix.
QueryAttribute(string delimiter, string prefix, string format)Also stores a value format for a scalar query value. It does not apply that format to flattened properties.string delimiter: nested-name separator; string prefix: name before flattened properties; string format: value format string.Attribute with the supplied delimiter, prefix, and format.
QueryAttribute.CollectionFormatGets the selected format, or sets an explicit format that overrides client settings.None.CollectionFormat; reads as RefitParameterFormatter until set, while IsCollectionFormatSpecified distinguishes that unset state.
QueryAttribute.DelimiterReturns the separator that joins the prefix and flattened property name.None. Read-only.string, default ".".
QueryAttribute.FormatGets or sets the format string for a scalar query value.None.string or null; default null.
QueryAttribute.IsCollectionFormatSpecifiedReports whether code assigned CollectionFormat, including through the collection-format constructor.None. Read-only.bool, default false.
QueryAttribute.PrefixReturns the name prepended to each flattened property.None. Read-only.string or null; default null.
QueryAttribute.SerializeNullControls whether a null property is written as an empty value instead of omitted.None.bool, default false.
QueryAttribute.TreatAsStringControls whether Refit uses an object's ToString() result instead of flattening its properties.None.bool, default false.
QueryNameAttributeAn attribute that creates a presence-style query flag from a parameter value.Applied to a parameter.Sealed Attribute type.
QueryNameAttribute()Marks a parameter whose formatted value becomes a bare query flag without =value.None.Attribute that omits null values and renders collection elements as separate flags.
QueryUriFormatAttributeAn attribute that controls how .NET renders a method's final request URI.Applied to a method.Sealed Attribute type.
QueryUriFormatAttribute(UriFormat uriFormat)Sets the .NET URI rendering mode for the method's complete path and query.UriFormat uriFormat: final URI rendering mode.Attribute applied to a method.
QueryUriFormatAttribute.UriFormatReturns the URI rendering mode supplied to the constructor.None. Read-only.UriFormat.

Shared query formatters

Full description and examples.

Types: Refit.CamelCaseUrlParameterKeyFormatter, Refit.DefaultFormUrlEncodedParameterFormatter, Refit.DefaultUrlParameterFormatter, Refit.DefaultUrlParameterKeyFormatter, Refit.IFormUrlEncodedParameterFormatter, Refit.IUrlParameterFormatter, Refit.IUrlParameterKeyFormatter, Refit.KebabCaseUrlParameterKeyFormatter, Refit.SnakeCaseUrlParameterKeyFormatter.

Choose a key naming rule

Full description and examples.

Key formatterFormat("PageSize")Settings shortcut
DefaultUrlParameterKeyFormatterPageSizeThe default settings.
CamelCaseUrlParameterKeyFormatterpageSizeRefitSettings.CamelCase()
SnakeCaseUrlParameterKeyFormatterpage_sizeRefitSettings.SnakeCase()
KebabCaseUrlParameterKeyFormatterpage-sizeRefitSettings.KebabCase()

API reference

Full description and examples.

APIDescriptionParametersReturns and behavior
IUrlParameterFormatter.Format(object? value, ICustomAttributeProvider attributeProvider, Type type)Defines how an implementation converts a URL parameter value.value: object; attributeProvider: ICustomAttributeProvider; type: containing TypeReturns string, or null to omit the value.
IFormUrlEncodedParameterFormatter.Format(object? value, string? formatString)Defines how an implementation converts a form-url-encoded field value.value: object; formatString: string format, which may be nullReturns string, or null to omit the field.
IUrlParameterKeyFormatter.Format(string key)Defines how an implementation converts a URL parameter name into its wire key.key: string keyReturns the formatted string key.
DefaultUrlParameterKeyFormatter()Creates the default key formatter.NoneCreates a formatter whose Format method returns each key unchanged.
DefaultUrlParameterKeyFormatter.Format(string key)Applies the identity naming rule to a URL parameter key.key: string keyReturns the same key.
CamelCaseUrlParameterKeyFormatter()Creates a key formatter that converts leading uppercase letters to camelCase.NoneCreates a camelCase key formatter.
CamelCaseUrlParameterKeyFormatter.Format(string key)Converts the leading uppercase run of a key to camelCase and leaves keys that do not start with uppercase unchanged.key: string keyReturns the camelCase string key.
SnakeCaseUrlParameterKeyFormatter()Creates a key formatter that separates words with underscores.NoneCreates a snake_case key formatter.
SnakeCaseUrlParameterKeyFormatter.Format(string key)Converts a key to snake_case.key: string keyReturns the snake_case string key.
KebabCaseUrlParameterKeyFormatter()Creates a key formatter that separates words with hyphens.NoneCreates a kebab-case key formatter.
KebabCaseUrlParameterKeyFormatter.Format(string key)Converts a key to kebab-case.key: string keyReturns the kebab-case string key.
DefaultFormUrlEncodedParameterFormatter()Creates the default form-url-encoded value formatter.NoneCreates an invariant-culture formatter that uses EnumMember values when available.
DefaultFormUrlEncodedParameterFormatter.Format(object? value, string? formatString)Formats a form value with an optional format string.value: object; formatString: string format, which may be nullReturns invariant-culture string text, uses an EnumMember value when available, and returns null for a null value.
DefaultUrlParameterFormatter()Creates the default URL value formatter.NoneCreates an invariant-culture formatter with no registered formats.
DefaultUrlParameterFormatter.AddFormat<TParameter>(string format)Registers a format for values whose runtime type is exactly TParameter.format: string format; TParameter: value typeReturns void; adding the same type twice throws ArgumentException. A non-blank query attribute format takes precedence.
DefaultUrlParameterFormatter.AddFormat<TContainer, TParameter>(string format)Registers a format for an exact TParameter value inside an exact TContainer type.format: string format; TContainer: containing type; TParameter: value typeReturns void; duplicate container/type registrations throw ArgumentException. A non-blank query attribute format takes precedence.
DefaultUrlParameterFormatter.Format(object? value, ICustomAttributeProvider attributeProvider, Type type)Formats a URL value using a query attribute format, a container-specific registration, or a general type registration.value: object; attributeProvider: ICustomAttributeProvider; type: containing TypeReturns invariant-culture string text, uses an EnumMember value when available, and returns null for a null value. Throws ArgumentNullException when attributeProvider is null.

Query converters

Full description and examples.

Types: Refit.IQueryConverter<T>, Refit.QueryConverterAttribute, Refit.SystemTextJsonQueryConverter<T>.

API reference

Full description and examples.

APIDescriptionParametersReturns and behavior
IQueryConverter<T>Defines a source-generated converter that writes one parameter's query pairs into a GeneratedQueryStringBuilder.T: the declared parameter type handled by the converter.Interface implemented by a custom query converter; generated request code caches one instance per converter type.
IQueryConverter<T>.Flatten(T value, string keyPrefix, ref GeneratedQueryStringBuilder builder, RefitSettings settings)Writes the non-null query pairs for value into builder, prefixing each key with keyPrefix.value: the declared query value; keyPrefix: the prefix from QueryAttribute, or an empty string; builder: the mutable query builder; settings: the active RefitSettings. No parameter has a default.void; appends pairs in place. The converter is used by generated requests and is not used by the reflection request builder.
QueryConverterAttributeMarks a query parameter for flattening by a specified IQueryConverter<T> implementation.None. Apply it to a method parameter.Attribute consumed by source-generated request code; the converter type must have a public parameterless constructor and match the parameter's declared type.
QueryConverterAttribute(Type converterType)Selects the converter type that generated request code instantiates for the annotated parameter.converterType: the Type implementing IQueryConverter<T>. No default.void; stores converterType in ConverterType.
QueryConverterAttribute.ConverterTypeIdentifies the converter implementation selected for the annotated parameter.None; read-only Type property.Type; returns the exact type passed to the constructor.
SystemTextJsonQueryConverter<T>Provides a JSON-metadata-based IQueryConverter<T> for nested, polymorphic, and otherwise runtime-shaped query values.T: the declared parameter type.Converter type; reads property names and getters from SystemTextJsonContentSerializer metadata.
SystemTextJsonQueryConverter<T>()Creates a JSON metadata query converter for the declared type T.None.Creates SystemTextJsonQueryConverter<T>; it does not capture a value or serializer.
SystemTextJsonQueryConverter<T>.Flatten(T value, string keyPrefix, ref GeneratedQueryStringBuilder builder, RefitSettings settings)Walks the runtime value's JSON metadata and appends scalar, nested-object, and collection values to builder.value: the root query value; keyPrefix: the prefix for its JSON property names; builder: the mutable query builder; settings: the active settings, including CollectionFormat and UrlParameterFormatter. No parameter has a default.void; omits null properties, uses dotted keys for nested objects, formats collection elements according to settings, and stops nested traversal at depth 32. Throws NotSupportedException unless settings.ContentSerializer is a SystemTextJsonContentSerializer.

Headers and authorization

Full description and examples.

Types: Refit.AuthorizeAttribute, Refit.HeaderAttribute, Refit.HeaderCollectionAttribute, Refit.HeadersAttribute.

Header order and validation

Full description and examples.

Attribute or propertyUse
Headers(params string[] headers) / HeadersShared interface or method headers.
Header(string header) / HeaderOne header value from a method argument.
HeaderCollection()A header dictionary from a method argument.
Authorize(string scheme = "Bearer") / SchemeAn authorization token from a method argument.
RefitSettings.AuthorizationHeaderValueGetterObtains a missing token before a declared authorized request is sent.
RefitSettings.ValidateHeadersChooses whether .NET validates header values.

Header attribute reference

Full description and examples.

MemberDescriptionParametersReturns or value
AuthorizeAttribute(string scheme = "Bearer")Declares that a method parameter supplies the token for an authorization header.string scheme: authorization scheme; default "Bearer".Creates an attribute that applies the scheme to a token parameter.
AuthorizeAttribute.SchemeGets the authorization scheme that Refit places before the token, such as Bearer or Basic.None. Read-only.string scheme supplied to the constructor.
HeaderAttribute(string header)Maps one method argument to a named request header.string header: header declaration.Creates an attribute that maps one method argument to the named request header.
HeaderAttribute.HeaderGets the HTTP header name that receives the method argument value.None. Read-only.string header declaration.
HeaderCollectionAttribute()Marks an argument whose dictionary supplies multiple request headers.None.Marker attribute for a header dictionary parameter.
HeadersAttribute(params string[] headers)Declares fixed headers that Refit adds to an interface or method request.params string[] headers: declarations; null becomes an empty array.Creates shared interface or method headers from the supplied declarations.
HeadersAttribute.HeadersGets the header declarations Refit applies to interface or method requests.None. Read-only.string[] declarations supplied to the constructor.

Local request context

Full description and examples.

Types: Refit.HttpRequestMessageOptions, Refit.PropertyAttribute.

Refit's option keys

Full description and examples.

Key propertyValue and use
InterfaceTypeThe top-level interface type for the call.
MethodNameThe declared method name, such as BuildAsync.
RelativePathTemplateThe unfilled route, such as /people/{id}. Use this stable name for request metrics.
RestMethodInfoReflected method details when the request-building path supplies them. Generated requests avoid this reflection.
MethodArgumentsThe argument array when CaptureMethodArguments is true.
RequestContentThe captured body text when CaptureRequestContent is true.

Request context reference

Full description and examples.

MemberDescriptionParametersReturns or value
PropertyAttributeMarks an interface property or method parameter whose value Refit copies to the request's local options or properties.None.Attribute type.
PropertyAttribute()Uses the marked property or parameter name as the request option key.None.A PropertyAttribute instance. The request value is stored under the inferred name.
PropertyAttribute(string key)Uses an explicit request option key instead of the marked property or parameter name.string key: key stored in Key.A PropertyAttribute instance.
PropertyAttribute.KeyGets the explicit key selected for the marked property or parameter.None. Read-only.Nullable string: the supplied key, or null when Refit infers the name.
HttpRequestMessageOptionsProvides the string keys that Refit uses for built-in request metadata and optional captured values.None. Static class.Static class. Its members return keys for HttpRequestMessage.Options or the older Properties dictionary.
HttpRequestMessageOptions.InterfaceTypeIdentifies the option that stores the top-level Refit interface type used for the request.None. Static read-only property.string "Refit.InterfaceType". The value stored under this key is a Type.
HttpRequestMessageOptions.RestMethodInfoIdentifies the option that stores reflected method details when the reflection request builder supplies them.None. Static read-only property.string "Refit.RestMethodInfo".
HttpRequestMessageOptions.MethodNameIdentifies the option that stores the declared Refit interface method name.None. Static read-only property.string "Refit.MethodName".
HttpRequestMessageOptions.RelativePathTemplateIdentifies the option that stores the unfilled route template for logging, metrics, and tracing.None. Static read-only property.string "Refit.RelativePathTemplate".
HttpRequestMessageOptions.RequestContentIdentifies the option that stores a captured request body string when CaptureRequestContent is enabled.None. Static read-only property.string "Refit.RequestContent".
HttpRequestMessageOptions.MethodArgumentsIdentifies the option that stores declared method arguments when CaptureMethodArguments is enabled.None. Static read-only property.string "Refit.MethodArguments". The value stored under this key is an object?[].

Request bodies

Full description and examples.

Types: Refit.BodyAttribute, Refit.BodySerializationMethod, Refit.RequestBodySerializationMode, Refit.RequestCompression, Refit.RequestCompressionOptions, Refit.TimeoutAttribute.

Choose a serialization method

Full description and examples.

BodySerializationMethodBehavior
Default = 0Passes HttpContent and streams through. Sends a string as plain text. Uses the configured serializer for other values.
Serialized = 3Uses the configured serializer, including for strings. A JSON string includes quotes.
UrlEncoded = 2Sends form key/value pairs. A dictionary or a generated property map supplies the fields.
JsonLines = 4Sends an enumerable as one serialized value per line. Register the element types with the JSON context.
Json = 1An obsolete name retained for compatibility. Use Serialized in new code.

Buffering and serialization modes

Full description and examples.

RequestBodySerializationModeBehavior
Default = 0Uses the serializer's usual content method. System.Text.Json uses its async metadata path.
Buffered = 1Uses ISynchronousContentSerializer to write a complete byte buffer.
Streamed = 2Uses that interface to write into the outgoing stream without storing the whole body.

Compression and ownership

Full description and examples.

RequestCompressionResult
Default = 0The attribute takes coding and level from settings. Settings set to Default do not compress.
None = 1No coding; an attribute can opt out of a settings-level coding.
GZip = 2Content-Encoding: gzip.
Brotli = 3Content-Encoding: br on .NET 8 and later.
Zstandard = 4Content-Encoding: zstd on .NET 11 and later.

API reference

Full description and examples.

APIDescriptionParameters or valueReturns and behavior
BodyAttributeMarks one interface-method parameter as the HTTP request body.Applies to a parameter.Refit uses the parameter value as HttpContent, stream content, plain text, or serialized content according to its type and SerializationMethod.
BodySerializationMethodSelects how Refit turns a body value into HTTP content.Enum values below.Use with BodyAttribute to choose text, serialized, form, or JSON Lines content.
RequestBodySerializationModeSelects how Refit writes serialized JSON request content.Enum values below.Configure through RefitSettings.RequestBodySerialization.
RequestCompressionSelects the content coding applied to a request body.Enum values below.Configure a default in RefitSettings or override it on BodyAttribute.
RequestCompressionOptionsHolds optional compressor-specific settings that replace the resolved compression level for each coding.Available on .NET 9 and later.Assign it to RefitSettings.RequestCompressionOptions.
TimeoutAttributeApplies a per-call timeout to a Refit interface method.Applies to a method.A positive timeout cancels the request when it elapses.
BodySerializationMethod.Default = 0Uses Refit's standard body rules.0Passes HttpContent and streams through, sends strings as plain text, and uses the configured serializer for other values.
BodySerializationMethod.Json = 1Retains the former name for serialized content.1; obsolete.Uses the configured serializer, including for strings. Use Serialized in new code.
BodySerializationMethod.UrlEncoded = 2Writes form URL-encoded content.2A dictionary or object's fields supply form keys and values.
BodySerializationMethod.Serialized = 3Serializes every body value with the configured content serializer.3Strings use the serializer too, so a JSON string includes its quotes.
BodySerializationMethod.JsonLines = 4Writes newline-delimited JSON.4Serializes each enumerable item with the configured serializer and writes one item per line.
RequestBodySerializationMode.Default = 0Uses the serializer's asynchronous JSON-content path.0System.Text.Json uses its metadata-based path.
RequestBodySerializationMode.Buffered = 1Serializes JSON into a complete byte buffer before sending.1; requires ISynchronousContentSerializer.Sends ByteArrayContent with Content-Length; suited to small and medium bodies.
RequestBodySerializationMode.Streamed = 2Writes JSON through a Utf8JsonWriter to the request stream.2; requires ISynchronousContentSerializer.Bounds peak memory with pooled chunks and does not set Content-Length; suited to large uploads.
RequestCompression.Default = 0Inherits the coding from RefitSettings.RequestCompression.0Uses the settings coding and level.
RequestCompression.None = 1Disables compression for this body.1Sends no content coding even when settings choose one.
RequestCompression.GZip = 2Compresses the body with gzip.2; every Refit target.Sends Content-Encoding: gzip.
RequestCompression.Brotli = 3Compresses the body with Brotli.3; .NET 8 and later.Sends Content-Encoding: br.
RequestCompression.Zstandard = 4Compresses the body with Zstandard.4; .NET 11 and later.Sends Content-Encoding: zstd.
BodyAttribute()Creates a body parameter attribute without overrides.None.Uses SerializationMethod.Default and leaves Buffered unset so settings decide.
BodyAttribute(bool buffered)Creates a body parameter attribute with an explicit buffering policy.buffered: bool.Sets Buffered; serialization remains Default.
BodyAttribute(BodySerializationMethod serializationMethod, bool buffered)Creates a body parameter attribute with explicit serialization and buffering policies.serializationMethod: BodySerializationMethod; buffered: bool.Sets both properties.
BodyAttribute(BodySerializationMethod serializationMethod)Creates a body parameter attribute with an explicit serialization method.serializationMethod: BodySerializationMethod.Sets SerializationMethod and leaves Buffered unset so settings decide.
RequestCompressionOptions()Creates empty compressor-specific settings.None; .NET 9 and later.All coding option properties are null, so compression uses its resolved level.
TimeoutAttribute(int milliseconds)Creates a method timeout attribute.milliseconds: int.A positive value applies the per-call deadline; zero or a negative value disables it.
BodyAttribute.BufferedGets the per-body buffering override.Read-only bool?.null uses RefitSettings.Buffered; true buffers content before sending and false skips it.
BodyAttribute.SerializationMethodGets the selected body serialization method.Read-only BodySerializationMethod; default Default.Determines how ordinary body values become HTTP content.
BodyAttribute.CompressionGets or sets a method-level request content coding.Settable RequestCompression; default Default.Default follows settings, while None opts this body out of a settings-level coding.
BodyAttribute.CompressionLevelGets or sets the compression effort for an explicitly selected coding.Settable CompressionLevel; default Optimal.Refit reads it only when Compression names a coding; otherwise settings provide the level.
RequestCompressionOptions.GZipGets or sets gzip-specific compressor settings.Settable ZLibCompressionOptions?.A non-null value replaces the resolved level for gzip; null uses that level.
RequestCompressionOptions.BrotliGets or sets Brotli-specific compressor settings.Settable BrotliCompressionOptions?.A non-null value replaces the resolved level for Brotli; null uses that level.
RequestCompressionOptions.ZstandardGets or sets Zstandard-specific compressor settings.Settable ZstandardCompressionOptions?; .NET 11 and later.A non-null value replaces the resolved level for Zstandard; null uses that level.
TimeoutAttribute.MillisecondsGets the timeout supplied to TimeoutAttribute.Read-only int, in milliseconds.The effective request deadline exists only when the value is positive.

Upload files with multipart requests

Full description and examples.

Types: Refit.AttachmentNameAttribute, Refit.ByteArrayPart, Refit.FileInfoPart, Refit.FormObjectAttribute, Refit.MultipartAttribute, Refit.MultipartItem, Refit.StreamPart.

Field names, file names and content types

Full description and examples.

InputForm field nameFile name sent
A part wrapper with Name setIts Name, overriding [AliasAs]Its nonempty FileName
A wrapper with Name = null[AliasAs], otherwise parameter nameIts nonempty FileName
A wrapper with empty FileNameThe same field-name rulesThe parameter's aliased or declared name
Raw Stream or byte[]Aliased or declared parameter nameThe same name
Raw FileInfoAliased or declared parameter nameFileInfo.Name
Raw HttpContentIts existing content-disposition metadataIts existing metadata
A string, formatted value or serialized modelAliased or declared parameter nameNone

API reference

Full description and examples.

APIDescriptionParameters or valueReturns and behavior
AttachmentNameAttribute(string name) (obsolete)Stores the legacy attachment file-name override. Use a part wrapper for new code.name: string to expose through NameCreates the obsolete attribute; using it produces compiler warning CS0618.
AttachmentNameAttribute.Name (obsolete)Gets the legacy file-name override.Read-only stringReturns the constructor's name.
ByteArrayPart(byte[] value, string fileName, string? contentType = null, string? name = null)Creates a multipart item backed by a byte array.value: byte[]; fileName: string; contentType: optional media type, default null; name: optional form field name, default nullStores the same byte array reference. Throws ArgumentNullException when value is null.
ByteArrayPart.ValueGets the bytes supplied to the constructor.Read-only byte[]Returns the original array.
ByteArrayPart.CreateContent() (protected override)Builds content for the byte-array part.NoneReturns ByteArrayContent over Value.
FileInfoPart(FileInfo value, string fileName, string? contentType = null, string? name = null)Creates a multipart item backed by a local file.value: FileInfo; fileName: string; contentType: optional media type, default null; name: optional form field name, default nullStores the file information. Throws ArgumentNullException when value is null; it opens the file only when content is created.
FileInfoPart.ValueGets the source file information.Read-only FileInfoReturns the original FileInfo.
FileInfoPart.CreateContent() (protected override)Opens the source file and builds content for the part.NoneReturns StreamContent over a newly opened read stream.
FormObjectAttribute()Marks a complex multipart parameter for property flattening.NoneCauses each public property to become a text part on the reflection request-builder path.
MultipartAttribute(string boundaryText = "----MyGreatBoundary")Marks an HTTP method as multipart and chooses its boundary.boundaryText: string, default "----MyGreatBoundary"Stores the boundary used to separate parts.
MultipartAttribute.BoundaryTextGets the boundary configured for the method.Read-only stringReturns the supplied boundary text.
MultipartItem(string fileName, string? contentType) (protected)Initializes a custom multipart item without an explicit form field name.fileName: string; contentType: optional media typeStores the file name and content type, with Name set to null. Throws ArgumentNullException for a null file name.
MultipartItem(string fileName, string? contentType, string? name) (protected)Initializes a custom multipart item with optional form field metadata.fileName: string; contentType: optional media type; name: optional form field nameStores all three values. A null file name throws ArgumentNullException.
MultipartItem.NameGets the explicit form field name for the item.Read-only string?Returns null when the constructor did not receive a name.
MultipartItem.ContentTypeGets the optional media type for the item content.Read-only string?Returns the configured content type, or null.
MultipartItem.FileNameGets the file name sent in the multipart disposition.Read-only stringReturns the required file name.
MultipartItem.ToContent()Creates this item's content and applies its nonempty ContentType.NoneReturns HttpContent. The caller disposes the returned content.
MultipartItem.CreateContent() (protected abstract)Defines how a derived item creates fresh underlying content.NoneReturns HttpContent; ToContent() applies the configured media type afterward.
StreamPart(Stream value, string fileName, string? contentType = null, string? name = null)Creates a multipart item backed by a caller-owned stream.value: Stream; fileName: string; contentType: optional media type, default null; name: optional form field name, default nullStores the stream without copying it. Throws ArgumentNullException when value is null; disposing its content leaves the caller's stream open.
StreamPart.ValueGets the caller-owned stream.Read-only StreamReturns the original stream.
StreamPart.CreateContent() (protected override)Wraps the stream without taking ownership of it.NoneReturns HttpContent that reads from Value.
AttachmentNameAttribute (obsolete)Legacy attribute for naming an attachment.NoneAttribute type; prefer the part wrapper types.
ByteArrayPartRepresents byte-array content with multipart metadata.NoneMultipart item type derived from MultipartItem.
FileInfoPartRepresents file content with multipart metadata.NoneMultipart item type derived from MultipartItem.
FormObjectAttributeMarks a complex parameter for multipart property flattening.NoneParameter attribute type.
MultipartAttributeMarks a method whose body contains named multipart parts.NoneMethod attribute type.
MultipartItemBase class for parts that carry a file name and optional content metadata.NoneAbstract type for custom multipart items.
StreamPartRepresents caller-owned stream content with multipart metadata.NoneMultipart item type derived from MultipartItem.

Results

Return types

Full description and examples.

Choose a shape

Full description and examples.

Return typeWhat happens
TaskSends the request and completes without a result value. See reading one reply.
Task<T>Sends the request and gives you one result to await. See reading one reply.
ValueTask<T>Sends the request and gives you one task-backed result to await. See reading one reply.
IObservable<T>Sends a fresh request per subscription and pushes one result. See querying a reply.
Task<ApiResponse<T>>Gives you a result wrapper with status, headers and a captured error. See keeping status and error details.
Task<IApiResponse<T>>Gives you the typed response wrapper through its interface. See response details.
Task<IApiResponse>Gives you response details without a typed reply body; the wrapper owns live response content. See response details.
Task<HttpRequestMessage>Builds a request and returns it without sending it; the caller owns and must dispose it.
Task<HttpResponseMessage>Returns the live HTTP response; the caller owns and must dispose it.
Task<HttpContent>Returns the live response content; the caller owns and must dispose it.
Task<Stream>Returns the live response body stream; the caller owns and must dispose it.
Task<ApiResponse<HttpResponseMessage>>Wraps the live HTTP response; the caller owns and must dispose it.
Task<ApiResponse<HttpContent>>Wraps the live response content; the caller owns and must dispose it.
Task<ApiResponse<Stream>>Wraps the live response body stream; the caller owns and must dispose it.
IAsyncEnumerable<T>Reads items from one streaming reply; the enumeration owns the live response until it ends.

Streaming replies

Full description and examples.

Reply formats

Full description and examples.

FormatContent typeBody shape
JsonArrayapplication/json, or another type not listed belowA JSON array such as [{"id":1,"name":"Ada"}].
JsonLinesapplication/jsonl, application/x-ndjson, or application/x-jsonlinesEach line holds a separate JSON value.
ServerSentEventstext/event-streamEach event's data: field holds a JSON value.

Response details and success checks

Full description and examples.

Types: Refit.ApiRequestException, Refit.ApiResponseExtensions, Refit.ApiResponse<T>, Refit.IApiResponse, Refit.IApiResponse<T>.

Status success and content success differ

Full description and examples.

PropertyMeaning
IsReceivedA response message exists. False means no response arrived.
IsSuccessStatusCodeA response exists and its status is 200–299.
IsSuccessfulThe status succeeds and Error is null.
HasContentContent is non-null. For a value type, its default value is also non-null.
IsSuccessfulWithContentBoth IsSuccessful and HasContent are true.
ContentThe deserialized reply value, or default when unavailable.
ErrorA captured ApiExceptionBase, or null. An unsuccessful manually constructed wrapper may have no error.
SettingsThe settings supplied to the concrete wrapper. It keeps the same instance.
RequestMessageThe request associated with this reply. The interface permits null; the concrete wrapper returns its constructor argument.
StatusCode, ReasonPhrase, VersionThe response status, reason text and HTTP version. Null when no response exists.
HeadersThe response headers. Null when no response exists.
ContentHeadersThe body headers, such as its media type. Null when unavailable.

Response API reference

Full description and examples.

MemberDescriptionParametersReturns or value
ApiRequestExceptionRepresents a failure while Refit sends a request before a response arrives.None.An ApiExceptionBase that retains request context and may wrap the sending exception.
ApiResponse<T>Wraps a deserialized body, HTTP metadata, settings, and a captured error.T: the body type.A sealed IApiResponse<T> that disposes the received response.
IApiResponseDefines status, metadata, error, and disposal members for a Refit response.None.The base response contract.
IApiResponse<T>Adds a covariant deserialized body and body-presence checks to IApiResponse.out T: the body type read by callers.The typed response contract.
ApiResponseExtensionsProvides success guards for generic and non-generic response interfaces.None.A static extension class.
ApiResponse<T>(HttpRequestMessage request, HttpResponseMessage? response, T? content, RefitSettings settings, ApiExceptionBase? error = null)Creates a response wrapper that keeps the request, optional HTTP response, deserialized content, settings, and captured error together.HttpRequestMessage request; HttpResponseMessage? response; T? content; RefitSettings settings; ApiExceptionBase? error = null.New response wrapper. response may be null for a transport failure; error defaults to null.
ApiResponse<T>(HttpResponseMessage response, T? content, RefitSettings settings)Creates a wrapper for a received response with no captured error.HttpResponseMessage response; T? content; RefitSettings settings.A new wrapper. response and response.RequestMessage must be non-null.
ApiResponse<T>(HttpResponseMessage response, T? content, RefitSettings settings, ApiExceptionBase? error)Creates a wrapper for a received response and a supplied captured error.HttpResponseMessage response; T? content; RefitSettings settings; ApiExceptionBase? error.A new wrapper. response and response.RequestMessage must be non-null.
ApiResponse<T>.Dispose()Disposes the received HTTP response once.None.void; it does not dispose RequestMessage.
ApiResponse<T>.EnsureSuccessStatusCodeAsync()Guards only the HTTP status.None.ValueTask<ApiResponse<T>>; returns this for 2xx. Otherwise it disposes and throws Error or a created ApiException; with no response it throws InvalidOperationException.
ApiResponse<T>.EnsureSuccessfulAsync()Guards the HTTP status and captured error.None.ValueTask<ApiResponse<T>>; returns this when IsSuccessful is true. Failure behavior matches the status guard.
ApiResponse<T>.HasRequestError(out ApiRequestException? error)Checks for a captured transport error and returns it through the out parameter.out ApiRequestException? error.bool; true when Error is a request error.
ApiResponse<T>.HasResponseError(out ApiException? error)Checks for a captured response error and returns it through the out parameter.out ApiException? error.bool; true when Error is a response error.
ApiResponse<T>.ContentStores the deserialized response body, or the default value when no body was read.None.T?: the stored response body, or default(T) when no value was read. For a non-nullable value type, this can be a value such as 0.
ApiResponse<T>.ContentHeadersExposes headers belonging to the received response body.None.HttpContentHeaders?: content headers, or null when no response content exists.
ApiResponse<T>.ErrorStores the captured transport, HTTP-status, or deserialization error.None.ApiExceptionBase?: the captured transport, HTTP, or deserialization error.
ApiResponse<T>.HasContentReports whether the deserialized Content is non-null.None.bool; Content is non-null.
ApiResponse<T>.IsSuccessfulWithContentReports whether the response succeeded without an error and has non-null Content.None.bool: true when the status is successful, no error was captured, and Content is non-null.
ApiResponse<T>.HeadersExposes headers from the received HTTP response.None.HttpResponseHeaders?: the received response headers, or null when no response arrived.
ApiResponse<T>.IsReceivedReports whether an HTTP response message was received.None.bool: true when an HTTP response arrived.
ApiResponse<T>.IsSuccessStatusCodeReports whether the received status code is in the 2xx range.None.bool: true when a received response has a 2xx status.
ApiResponse<T>.IsSuccessfulReports whether the status is 2xx and no error was captured; it does not require content.None.bool: true when the status is 2xx and no error was captured. It does not promise body content.
ApiResponse<T>.ReasonPhraseExposes the reason phrase returned with the HTTP status.None.string?: the server reason phrase, or null when none is available.
ApiResponse<T>.RequestMessageExposes the request associated with the response wrapper.None.HttpRequestMessage: the request associated with this wrapper.
ApiResponse<T>.SettingsExposes the RefitSettings used to process the response.None.RefitSettings: the settings instance supplied to the constructor.
ApiResponse<T>.StatusCodeExposes the received HTTP status code, or null when no response arrived.None.HttpStatusCode?: the received status, or null when no response arrived.
ApiResponse<T>.VersionExposes the HTTP version used by the received response.None.Version?: the received HTTP version, or null when no response arrived.
IApiResponse.HasRequestError(out ApiRequestException? error)Checks for a captured transport error and returns it through the out parameter.out ApiRequestException? error.bool: true and assigns the transport error when the request failed before a response; otherwise false and null.
IApiResponse.HasResponseError(out ApiException? error)Checks for a captured response error and returns it through the out parameter.out ApiException? error.bool: true and assigns the response or body-reading error; otherwise false and null.
IApiResponse.HeadersExposes headers from the received HTTP response.None.HttpResponseHeaders?: the received response headers, or null when no response arrived.
IApiResponse.ContentHeadersExposes headers belonging to the received response body.None.HttpContentHeaders?: headers for the received response body, or null when they are unavailable.
IApiResponse.IsReceivedReports whether an HTTP response message was received.None.bool: true when an HTTP response arrived.
IApiResponse.IsSuccessStatusCodeReports whether the received status code is in the 2xx range.None.bool: true when a received response has a 2xx status.
IApiResponse.IsSuccessfulReports whether the status is 2xx and no error was captured; it does not require content.None.bool: true when the status is 2xx and no error was captured. It does not promise body content.
IApiResponse.StatusCodeExposes the received HTTP status code, or null when no response arrived.None.HttpStatusCode?: the received status, or null when no response arrived.
IApiResponse.ReasonPhraseExposes the reason phrase returned with the HTTP status.None.string?: the server reason phrase, or null when none is available.
IApiResponse.RequestMessageExposes the request associated with the response wrapper.None.HttpRequestMessage?: the request that led to the response, or null when unavailable.
IApiResponse.VersionExposes the HTTP version used by the received response.None.Version?: the received HTTP version, or null when no response arrived.
IApiResponse.ErrorStores the captured transport, HTTP-status, or deserialization error.None.ApiExceptionBase?: a captured transport, HTTP, or deserialization error. An unsuccessful response can have no captured error.
IApiResponse<T>.ContentStores the deserialized response body, or the default value when no body was read.None.T?: the stored response body, or default(T) when no value was read. For a non-nullable value type, this can be a value such as 0.
IApiResponse<T>.HasContentReports whether the deserialized Content is non-null.None.bool: true when Content is non-null.
IApiResponse<T>.IsSuccessfulWithContentReports whether the response succeeded without an error and has non-null Content.None.bool: true when IsSuccessful is true and Content is non-null.
ApiRequestException(HttpRequestMessage message, HttpMethod httpMethod, RefitSettings refitSettings, Exception innerException)Creates a transport exception with the request, HTTP method, settings, and supplied message or inner cause.HttpRequestMessage message; HttpMethod httpMethod; RefitSettings refitSettings; Exception innerException.New transport exception using the non-null cause's message.
ApiRequestException(string exceptionMessage, HttpRequestMessage message, HttpMethod httpMethod, RefitSettings refitSettings)Creates a transport exception with the request, HTTP method, settings, and supplied message or inner cause.string exceptionMessage; HttpRequestMessage message; HttpMethod httpMethod; RefitSettings refitSettings.New transport exception with the supplied message.
ApiRequestException(string exceptionMessage, HttpRequestMessage message, HttpMethod httpMethod, RefitSettings refitSettings, Exception? innerException)Creates a transport exception with the request, HTTP method, settings, and supplied message or inner cause.string exceptionMessage; HttpRequestMessage message; HttpMethod httpMethod; RefitSettings refitSettings; Exception? innerException.New transport exception with the supplied message and optional cause.
ApiResponseExtensions.EnsureSuccessStatusCodeAsync<T>(IApiResponse<T> response)Guards only the HTTP status of a typed response.IApiResponse<T> response.ValueTask<IApiResponse<T>>; returns the same response for 2xx. It rejects null, and otherwise throws Error or InvalidOperationException without disposing.
ApiResponseExtensions.EnsureSuccessfulAsync<T>(IApiResponse<T> response)Guards the HTTP status and captured error of a typed response.IApiResponse<T> response.ValueTask<IApiResponse<T>>; returns the same response when IsSuccessful is true. Failure behavior matches the status guard.
ApiResponseExtensions.EnsureSuccessStatusCodeAsync(IApiResponse response)Guards only the HTTP status of a non-generic response.IApiResponse response.ValueTask<IApiResponse>; returns the same response for 2xx. It rejects null, and otherwise throws Error or InvalidOperationException without disposing.
ApiResponseExtensions.EnsureSuccessfulAsync(IApiResponse response)Guards the HTTP status and captured error of a non-generic response.IApiResponse response.ValueTask<IApiResponse>; returns the same response when IsSuccessful is true. Failure behavior matches the status guard.

Error bodies and problem details

Full description and examples.

Types: Refit.ApiException, Refit.ApiExceptionBase, Refit.DefaultApiExceptionFactory, Refit.ProblemDetails, Refit.ValidationApiException.

Shared request details

Full description and examples.

PropertyMeaning
HttpMethodThe method supplied for the failed call.
RequestMessageThe request, including its headers and local options.
UriRequestMessage.RequestUri, which can be null.
RefitSettingsThe settings retained for the call and later error-body reading.
RequestContentCaptured request-body text when enabled; you can replace it to remove private data.
HasRequestContentThe captured text is neither null nor empty. Whitespace counts as present.

Standard validation replies

Full description and examples.

ProblemDetails propertyMeaning
TypeA URI identifying the kind of problem; defaults to about:blank.
TitleA short label for that kind of problem.
StatusThe status in the JSON document. It does not replace the actual HTTP status.
DetailText about this occurrence.
InstanceA URI identifying this occurrence.
ErrorsA mutable dictionary from field name to an array of validation messages. Empty by default.
ExtensionsA mutable dictionary for other JSON properties. Empty by default.

Error API reference

Full description and examples.

MemberDescriptionParametersReturns or value
ApiExceptionBaseAbstract base class for Refit exceptions that retain the failed request, its HTTP method, and the settings used for the call.None.Base for request-send and response exceptions.
ApiExceptionBase(HttpRequestMessage message, HttpMethod httpMethod, RefitSettings refitSettings, Exception innerException)Initializes an error with the request context and a required underlying exception.HttpRequestMessage message; HttpMethod httpMethod; RefitSettings refitSettings; Exception innerException.Protected base constructor using the non-null cause's message.
ApiExceptionBase(string exceptionMessage, HttpRequestMessage message, HttpMethod httpMethod, RefitSettings refitSettings)Initializes an error with a caller-supplied message and request context.string exceptionMessage; HttpRequestMessage message; HttpMethod httpMethod; RefitSettings refitSettings.Protected base constructor with the supplied message.
ApiExceptionBase(string exceptionMessage, HttpRequestMessage message, HttpMethod httpMethod, RefitSettings refitSettings, Exception? innerException)Initializes an error with a caller-supplied message, request context, and optional cause.string exceptionMessage; HttpRequestMessage message; HttpMethod httpMethod; RefitSettings refitSettings; Exception? innerException.Protected base constructor with an optional cause.
ApiExceptionBase.HttpMethodIdentifies the HTTP method that Refit used for the failed request.None.HttpMethod: the method used by the failed call.
ApiExceptionBase.UriExposes the request URI when the retained request has one.None.Uri?: RequestMessage.RequestUri.
ApiExceptionBase.RequestMessageGives access to the live request, including headers and request options.None.HttpRequestMessage: the request, including its headers and local options.
ApiExceptionBase.RequestContentHolds request-body text captured before sending when CaptureRequestContent is enabled.string? value.Captured request-body text. You can replace it to remove private data.
ApiExceptionBase.HasRequestContentLets you test whether captured request text is available without checking the property yourself.None.bool: true when captured request text is not null or empty. Whitespace counts as present.
ApiExceptionBase.RefitSettingsGets the settings that governed the failed call.None.RefitSettings: settings retained for the call and later error-body reading.
ApiExceptionRepresents an error received after the server sent an HTTP response.None.Exception with response status, headers, and buffered body text.
ApiException(HttpRequestMessage message, HttpMethod httpMethod, string? content, HttpStatusCode statusCode, string? reasonPhrase, HttpResponseHeaders headers, RefitSettings refitSettings)Initializes a response exception with Refit's status-and-reason message.HttpRequestMessage message; HttpMethod httpMethod; string? content; HttpStatusCode statusCode; string? reasonPhrase; HttpResponseHeaders headers; RefitSettings refitSettings.Protected HTTP-response constructor.
ApiException(HttpRequestMessage message, HttpMethod httpMethod, string? content, HttpStatusCode statusCode, string? reasonPhrase, HttpResponseHeaders headers, RefitSettings refitSettings, Exception? innerException)Initializes a response exception with Refit's status-and-reason message and an optional underlying cause.HttpRequestMessage message; HttpMethod httpMethod; string? content; HttpStatusCode statusCode; string? reasonPhrase; HttpResponseHeaders headers; RefitSettings refitSettings; Exception? innerException.Protected HTTP-response constructor with an optional cause.
ApiException(string exceptionMessage, HttpRequestMessage message, HttpMethod httpMethod, string? content, HttpStatusCode statusCode, string? reasonPhrase, HttpResponseHeaders headers, RefitSettings refitSettings)Initializes a response exception with an app-defined message.string exceptionMessage; HttpRequestMessage message; HttpMethod httpMethod; string? content; HttpStatusCode statusCode; string? reasonPhrase; HttpResponseHeaders headers; RefitSettings refitSettings.Protected HTTP-response constructor with the supplied message.
ApiException(string exceptionMessage, HttpRequestMessage message, HttpMethod httpMethod, string? content, HttpStatusCode statusCode, string? reasonPhrase, HttpResponseHeaders headers, RefitSettings refitSettings, Exception? innerException)Initializes a response exception with an app-defined message and an optional underlying cause.string exceptionMessage; HttpRequestMessage message; HttpMethod httpMethod; string? content; HttpStatusCode statusCode; string? reasonPhrase; HttpResponseHeaders headers; RefitSettings refitSettings; Exception? innerException.Protected HTTP-response constructor with the supplied message and optional cause.
ApiException.Create(HttpRequestMessage message, HttpMethod httpMethod, HttpResponseMessage response, RefitSettings refitSettings)Builds an ApiException asynchronously from the failed HTTP response and request metadata.HttpRequestMessage message; HttpMethod httpMethod; HttpResponseMessage response; RefitSettings refitSettings.Task<ApiException> that captures the unsuccessful response.
ApiException.Create(HttpRequestMessage message, HttpMethod httpMethod, HttpResponseMessage response, RefitSettings refitSettings, Exception? innerException)Builds an ApiException asynchronously from the failed HTTP response and request metadata.HttpRequestMessage message; HttpMethod httpMethod; HttpResponseMessage response; RefitSettings refitSettings; Exception? innerException.Task<ApiException> that captures the response and optional cause.
ApiException.Create(string exceptionMessage, HttpRequestMessage message, HttpMethod httpMethod, HttpResponseMessage response, RefitSettings refitSettings)Builds an ApiException asynchronously from the failed HTTP response and request metadata.string exceptionMessage; HttpRequestMessage message; HttpMethod httpMethod; HttpResponseMessage response; RefitSettings refitSettings.Task<ApiException> with the supplied message.
ApiException.Create(string exceptionMessage, HttpRequestMessage message, HttpMethod httpMethod, HttpResponseMessage response, RefitSettings refitSettings, Exception? innerException)Builds an ApiException asynchronously from the failed HTTP response and request metadata.string exceptionMessage; HttpRequestMessage message; HttpMethod httpMethod; HttpResponseMessage response; RefitSettings refitSettings; Exception? innerException.Task<ApiException> with the supplied message and optional cause.
ApiException.GetContentAsAsync<T>()Deserializes buffered response text through the configured asynchronous content serializer.None; T is the requested error-body type.Task<T?>; asynchronous deserialization.
ApiException.GetContentAs<T>()Deserializes buffered response text through the configured synchronous content serializer.None; T is the requested error-body type.T?; synchronous deserialization or NotSupportedException.
ApiException.TryGetContentAs<T>(out T? content)Tries synchronous error-body deserialization without letting parsing or serializer-support failures escape.out T? content.bool; false for absent, unsupported, or invalid content.
ApiException.StatusCodeIdentifies the HTTP status sent by the server.None.HttpStatusCode: the received HTTP response status.
ApiException.ReasonPhrasePreserves the optional reason phrase sent with the HTTP status.None.string?: the server reason phrase, if supplied.
ApiException.HeadersProvides the response headers retained from the failed response.None.HttpResponseHeaders: the received response headers.
ApiException.ContentHeadersProvides headers belonging to the buffered response body.None; protected setter.HttpContentHeaders?: headers for the captured response body.
ApiException.ContentHolds the raw buffered response body and lets a redactor replace or clear it.string? value.Captured raw response text. You can replace it to remove private data.
ApiException.HasContentTests whether Content contains non-whitespace response text.None.bool: true when Content is not null, empty, or whitespace.
DefaultApiExceptionFactorySupplies Refit's default conversion from an unsuccessful HTTP response to an ApiException.None.Response-to-exception factory.
DefaultApiExceptionFactory(RefitSettings refitSettings)Creates the exception factory that turns unsuccessful responses into ApiException instances using the supplied settings.RefitSettings refitSettings: settings used to create exceptions.New factory.
DefaultApiExceptionFactory.CreateAsync(HttpResponseMessage responseMessage)Returns no exception for a successful response, or creates an ApiException from an unsuccessful response's retained request.HttpResponseMessage responseMessage.ValueTask<Exception?>; null for a successful response.
ProblemDetailsModels a standard HTTP problem document, including validation errors and extension fields.None.Data object used by ValidationApiException.
ProblemDetails()Initializes a problem document with empty Errors and Extensions, and Type set to about:blank.None.New problem-details object with empty Errors/Extensions and Type "about:blank".
ProblemDetails.ErrorsMaps each invalid field name to its validation messages.None; init only.Dictionary<string, string[]>; default empty.
ProblemDetails.ExtensionsStores JSON properties that are not standard problem-details fields.None; init only.IDictionary<string, object>; default empty.
ProblemDetails.TypeIdentifies the kind of problem, usually with a URI.string? value.A URI that identifies the problem kind; default about:blank.
ProblemDetails.TitleGives a short human-readable label for the problem kind.string? value.A short label for the problem kind; default null.
ProblemDetails.StatusCarries the status recorded in the JSON problem document.int value.The status value carried in the problem document; default 0. It does not replace the actual HTTP status.
ProblemDetails.DetailExplains this particular problem occurrence.string? value.Text about this problem occurrence; default null.
ProblemDetails.InstanceIdentifies this particular problem occurrence, usually with a URI.string? value.A URI that identifies this problem occurrence; default null.
ValidationApiExceptionRepresents an API error whose body has been parsed as standard problem details.None.ApiException subtype with typed validation content.
ValidationApiException(string message)Creates a validation exception for app code that has no received problem response to convert.string message.New validation exception with synthetic HTTP context.
ValidationApiException(string message, Exception innerException)Creates a validation exception with an app-defined message and a required cause.string message; Exception innerException: non-null cause.New validation exception with cause.
ValidationApiException.Create(ApiException exception)Parses the non-blank raw body of an existing API exception as standard problem details.ApiException exception: error to convert; it must contain non-whitespace content.ValidationApiException with ProblemDetails content.
ValidationApiException.ContentExposes the parsed problem document while hiding ApiException.Content on a validation exception.None; private setter.ProblemDetails?: the parsed validation body, or null when this exception was created only with a message.

Custom return adapters

Full description and examples.

Types: Refit.IReturnTypeAdapter<TReturn, TResult>.

Adapter reference

Full description and examples.

MemberDescriptionParametersReturns or value
TReturn IReturnTypeAdapter<TReturn, TResult>.Adapt(Func<CancellationToken, Task<TResult>> invoke)Converts the deferred HTTP operation into the custom return shape.Func<CancellationToken, Task<TResult>> invoke: deferred HTTP invocation.TReturn: the wrapper value surfaced by the interface method.
RefitSettings.ReturnTypeAdaptersExposes the adapter types that the opt-in reflection request builder uses to create custom return shapes.None. Read-only IList<Type> property; add a closed adapter type or supported open generic definition. Each entry is a Type.Mutable adapter registry, initialized empty. Reflection builds consult it; source generation discovers adapters at compile time.
IReturnTypeAdapter<TReturn, TResult>Defines the contract for converting a deferred HTTP call into the return type exposed by a Refit interface method.TReturn: surfaced wrapper type. TResult: deserialized response body type.Implement Adapt to return the wrapper.

Serialization

JSON and generated metadata

Full description and examples.

Types: Refit.IHttpContentSerializer, Refit.ISynchronousContentDeserializer, Refit.ISynchronousContentSerializer, Refit.SystemTextJsonContentSerializer.

Serializer capabilities

Full description and examples.

InterfaceDescription
IHttpContentSerializerDefines the required request-body writer, response-body reader and reflected property-name hook.
ISynchronousContentSerializerAdds synchronous buffered and streamed request-body writers. Refit uses them for Buffered and Streamed request-body modes.
ISynchronousContentDeserializerAdds a reader for an error body that Refit has already buffered as a string.
IStreamingContentSerializerAdds an incremental response reader for Refit interface methods that return IAsyncEnumerable<T>.
APIDescriptionParametersReturns and behavior
SystemTextJsonContentSerializer()Creates a serializer with Refit's default JSON configuration.NoneCreates and retains a new JsonSerializerOptions from GetDefaultJsonSerializerOptions().
SystemTextJsonContentSerializer(JsonSerializerOptions jsonSerializerOptions)Creates a serializer with the supplied JSON configuration.jsonSerializerOptions: JsonSerializerOptions that controls JSON conversion and metadata lookup.Retains and uses the supplied JsonSerializerOptions instance.
SerializerOptionsGets the configuration used by this serializer.NoneReturns the same JsonSerializerOptions instance passed to the constructor or created by the default constructor.
GetDefaultJsonSerializerOptions()Creates Refit's general-purpose JSON configuration.NoneReturns a fresh mutable JsonSerializerOptions with camel-case names, case-insensitive matching, string-number reading, and Refit's object and enum converters.
GetFastPathJsonSerializerOptions()Creates options that can use System.Text.Json's source-generated serialization fast path after you assign generated metadata.NoneReturns a fresh mutable JsonSerializerOptions with camel-case names and case-insensitive matching, without Refit converters or custom number handling.
ToHttpContent<T>(T item)Serializes a request value through Refit's normal asynchronous JSON-content path.item: T, the request value to serialize.Returns JSON HttpContent. It uses configured generated metadata when available; an interface or abstract T without polymorphism configuration uses the non-null value's runtime type.
ToHttpContentSynchronous<T>(T item)Serializes a request value immediately into a buffered JSON body.item: T, the request value to serialize.Returns UTF-8 JSON HttpContent with a ByteArrayContent body and application/json; charset=utf-8 content type.
ToStreamingHttpContent<T>(T item)Creates a request body that serializes a value when the HTTP request sends it.item: T, the request value to serialize.Returns HttpContent that writes UTF-8 JSON to the request stream with application/json; charset=utf-8 content type.
FromHttpContentAsync<T>(HttpContent content, CancellationToken cancellationToken = default)Reads a JSON HTTP body as a value.content: HttpContent, the response body; cancellationToken: CancellationToken that cancels the read. Default: default.Returns Task<T?> for the deserialized value.
DeserializeFromString<T>(string content)Reads an already buffered JSON string.content: string, the JSON text.Returns T?, the deserialized value. Invalid JSON throws JsonException.
DeserializeStreamAsync<T>(Stream stream, StreamingContentFormat format, CancellationToken cancellationToken = default)Reads one JSON value at a time from a framed response stream.stream: Stream, the response body; format: StreamingContentFormat, its JSON array, JSON Lines, or SSE framing; cancellationToken: CancellationToken that cancels enumeration. Default: default.Returns IAsyncEnumerable<T?> that yields values as they arrive. See streaming replies.
GetFieldNameForProperty(PropertyInfo propertyInfo)Finds a property's explicit JSON field name for reflected integrations.propertyInfo: PropertyInfo, the property to inspect.Returns the JsonPropertyNameAttribute name, or null when the property has no such attribute.

Defaults and fast-path writers

Full description and examples.

ConditionWhat to do
Generated writer existsUse Default or Serialization generation mode. Keep metadata too when you read replies.
No custom convertersAvoid entries in JsonSerializerOptions.Converters and JsonConverter attributes on the model or its members.
Compatible optionsKeep naming, ignored-member and null-handling options aligned with the generated context.
Supported featuresAvoid custom encoders, dictionary key policies and reference handling for this path.
Supported number writingAvoid number handling that changes JSON output, such as WriteAsString. AllowReadingFromString alone does not block writing.

Newtonsoft.Json content

Full description and examples.

Types: Refit.NewtonsoftJsonContentSerializer.

Method reference

Full description and examples.

APIDescriptionParametersReturns and behavior
NewtonsoftJsonContentSerializerImplements Refit's IHttpContentSerializer with Newtonsoft.Json. It also implements ISynchronousContentDeserializer.No public properties.Creates JSON request content, reads JSON response content, exposes buffered string deserialization, and maps explicit JSON property names for Refit.
NewtonsoftJsonContentSerializer()Creates a serializer with lazily resolved default settings.None.Returns NewtonsoftJsonContentSerializer. The default path invokes JsonConvert.DefaultSettings, creates JsonSerializerSettings when needed, and forces TypeNameHandling.None.
NewtonsoftJsonContentSerializer(JsonSerializerSettings? jsonSerializerSettings)Creates a serializer with caller-supplied Newtonsoft.Json settings.jsonSerializerSettings: nullable JsonSerializerSettings; null selects the default-settings path.Returns NewtonsoftJsonContentSerializer and retains a non-null settings object as supplied.
ToHttpContent<T>(T item)Serializes a value to JSON request content.item: value of generic type T to serialize.Returns HttpContent containing UTF-8 JSON with media type application/json.
FromHttpContentAsync<T>(HttpContent content, CancellationToken cancellationToken = default)Buffers and deserializes HTTP response content asynchronously.content: HttpContent to read; cancellationToken: CancellationToken, default CancellationToken.None.Returns Task<T?>. A null content value returns default; otherwise the method reads the content using its charset or UTF-8, deserializes it, and disposes the read stream.
DeserializeFromString<T>(string content)Deserializes an already buffered JSON string synchronously.content: string containing JSON.Returns nullable generic T? from JsonConvert.DeserializeObject<T>. Newtonsoft.Json exceptions can propagate for invalid JSON.
GetFieldNameForProperty(PropertyInfo propertyInfo)Finds the JSON field name that an object property declares explicitly.propertyInfo: PropertyInfo to inspect.Returns the JsonPropertyAttribute.PropertyName, or null when the property has no JsonPropertyAttribute. Throws ArgumentNullException when propertyInfo is null.

XML content

Full description and examples.

Types: Refit.XmlContentSerializer, Refit.XmlContentSerializerSettings, Refit.XmlReaderWriterSettings.

Settings reference

Full description and examples.

XmlContentSerializerSettings memberDescriptionDefault and purpose
XmlContentSerializerSettings()Creates settings for XML request and response serialization.XmlDefaultNamespace is null; reader/writer settings are new; namespaces contain one empty-prefix/empty-namespace mapping; attribute overrides are empty.
XmlDefaultNamespacestring?; the default XML namespace passed when constructing a serializer for deserialization.null means no default namespace. The value is used when the type's serializer is first cached for reading.
XmlReaderWriterSettingsXmlReaderWriterSettings; the paired reader and writer configuration.Defaults to a new instance. Accessing its reader or writer applies asynchronous operation and safe DTD settings.
XmlNamespacesXmlSerializerNamespaces; namespace prefixes and URIs supplied to XmlSerializer.Serialize.Defaults to one empty-prefix/empty-namespace mapping.
XmlAttributeOverridesXmlAttributeOverrides; alternate XML mappings for model types.Defaults to an empty collection. Overrides are read when a type's cached XmlSerializer is created.
XmlReaderWriterSettings memberDescriptionBehavior
XmlReaderWriterSettings()Creates paired XML reader and writer settings.Both settings are new defaults.
XmlReaderWriterSettings(XmlReaderSettings readerSettings)Takes reader settings and creates the writer settings.Retains readerSettings; the writer settings are new defaults. A null argument throws ArgumentNullException.
XmlReaderWriterSettings(XmlWriterSettings writerSettings)Takes writer settings and creates the reader settings.Retains writerSettings; the reader settings are new defaults. A null argument throws ArgumentNullException.
XmlReaderWriterSettings(XmlReaderSettings readerSettings, XmlWriterSettings writerSettings)Takes both caller-supplied settings.Retains both objects. Either null argument throws ArgumentNullException.
ReaderSettingsXmlReaderSettings; gets or replaces the reader settings.Assignment rejects null. Getting the value sets Async = true; unless AllowDtdProcessing is enabled, it also sets DtdProcessing.Prohibit and clears XmlResolver.
WriterSettingsXmlWriterSettings; gets or replaces the writer settings.Assignment rejects null. Getting the value sets Async = true.
AllowDtdProcessingbool; compatibility opt-out from Refit's DTD hardening.Defaults to false and is obsolete. Setting it to true leaves caller-configured DTD processing and resolver settings in place.

Method reference

Full description and examples.

XmlContentSerializer memberDescriptionParametersReturns and behavior
XmlContentSerializer()Creates an XML content serializer with default settings.NoneUses a new XmlContentSerializerSettings.
XmlContentSerializer(XmlContentSerializerSettings settings)Creates an XML content serializer with caller-supplied settings.settings: non-null XmlContentSerializerSettingsStores the settings; null throws ArgumentNullException.
ToHttpContent<T>(T item)Serializes a value for an XML HTTP request.item: value to serializeReturns HttpContent with media type application/xml and the configured writer charset. null throws ArgumentNullException. The runtime type selects the cached XmlSerializer.
FromHttpContentAsync<T>(HttpContent content, CancellationToken cancellationToken = default)Reads and deserializes an XML HTTP response.content: HttpContent to read; cancellationToken: CancellationToken, default defaultReturns Task<T?>. It buffers the content as a string, then parses it synchronously with the serializer for T; cancellation applies while reading the content.
DeserializeFromString<T>(string content)Deserializes buffered XML text.content: string containing XMLReturns T? parsed with the configured reader, default namespace, and attribute overrides.
GetFieldNameForProperty(PropertyInfo propertyInfo)Finds the XML field name declared on a property.propertyInfo: PropertyInfo to inspectReturns the ElementName from an XmlElementAttribute, otherwise the AttributeName from an XmlAttributeAttribute, otherwise null. A null property throws ArgumentNullException.

Content writers and stream readers

Full description and examples.

Types: Refit.IStreamingContentSerializer, Refit.JsonContentSerializer, Refit.JsonLinesContent, Refit.ObjectToInferredTypesConverter, Refit.StreamingContentFormat.

Read a stream directly

Full description and examples.

FormatBody framing
JsonArray = 0One top-level JSON array; each array element is yielded.
JsonLines = 1JSON values separated by whitespace on .NET 9 and later.
ServerSentEvents = 2An SSE stream; each event's data payload is deserialized as JSON.

Infer values stored as object

Full description and examples.

JSON tokenResult
true or falsebool
Number representable as Int64long
Other numberdouble
String parseable as DateTimeDateTime
Other stringstring
Object, array or a directly read null tokenA detached JsonElement

API reference

Full description and examples.

APIDescriptionParametersReturns and behavior
StreamingContentFormatNames the framing used by a streaming content serializer.NoneAn enum with JsonArray, JsonLines, and ServerSentEvents values.
StreamingContentFormat.JsonArray = 0Selects one top-level JSON array.NoneEach array element is yielded as one T value.
StreamingContentFormat.JsonLines = 1Selects newline-delimited JSON values.NoneEach JSON value is yielded as one T value.
StreamingContentFormat.ServerSentEvents = 2Selects server-sent events.NoneEach event's data field is deserialized and yielded as one T value.
IStreamingContentSerializerDefines the optional capability to deserialize response bodies incrementally.NoneImplement this interface when a serializer can produce an IAsyncEnumerable<T> without buffering the complete body.
JsonContentSerializer (obsolete)Names the obsolete JSON serializer retained for binary compatibility.NoneA public class implementing IHttpContentSerializer; its compiler error prevents direct use.
JsonLinesContentRepresents an HTTP body that writes one serialized value per JSON Lines record.NoneA sealed HttpContent implementation.
ObjectToInferredTypesConverterInfers CLR values when System.Text.Json deserializes a value declared as object.NoneA JsonConverter<object>.
JsonLinesContent(IEnumerable items, IHttpContentSerializer serializer)Creates HTTP content that serializes each item as one JSON Lines record.items: IEnumerable values to write; serializer: IHttpContentSerializer for each valueCreates HttpContent. Throws ArgumentNullException for either argument.
JsonLinesContent.JsonLinesMediaTypeIdentifies the media type emitted by JSON Lines content.NoneReturns string application/x-ndjson.
JsonLinesContent.SerializeToStreamAsync(Stream stream, TransportContext? context) (protected override)Serializes each item to the destination stream as one newline-delimited JSON record.stream: Stream destination; context: unused TransportContextReturns Task and writes each serialized value with LF separators and no trailing LF.
JsonLinesContent.TryComputeLength(out long length) (protected override)Reports whether the JSON Lines content has a known byte length.length: long receives -1Returns bool false; the content has no advertised length.
IStreamingContentSerializer.DeserializeStreamAsync<T>(Stream stream, StreamingContentFormat format, CancellationToken cancellationToken = default)Reads a response stream according to its framing format and yields deserialized values as they arrive.stream: Stream source; format: StreamingContentFormat framing; cancellationToken: CancellationToken used to cancel enumerationReturns IAsyncEnumerable<T?>. Malformed data or missing metadata fails during enumeration.
JsonContentSerializer() (obsolete)Represents the obsolete JSON serializer compatibility type.NoneConstructs the compatibility type, but direct use is a compiler error because the type is obsolete with error: true.
JsonContentSerializer.ToHttpContent<T>(T item) (obsolete)Attempts to serialize item into HTTP content.item: generic value to serializeReturns HttpContent in the signature, but always throws NotSupportedException.
JsonContentSerializer.FromHttpContentAsync<T>(HttpContent content, CancellationToken cancellationToken = default) (obsolete)Attempts to deserialize content as T.content: HttpContent source; cancellationToken: CancellationToken cancellationReturns Task<T?> in the signature, but always throws NotSupportedException.
JsonContentSerializer.GetFieldNameForProperty(PropertyInfo propertyInfo) (obsolete)Attempts to calculate a serialized field name for a reflected property.propertyInfo: PropertyInfo to inspectReturns string in the signature, but always throws NotSupportedException.
ObjectToInferredTypesConverter()Creates the converter used to infer CLR values when deserializing object.NoneCreates a JsonConverter<object>.
ObjectToInferredTypesConverter.Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)Reads one JSON token and converts it to the appropriate CLR value.Utf8JsonReader, Type, JsonSerializerOptionsReturns nullable object, inferring scalar CLR types and retaining objects/arrays as JsonElement.
ObjectToInferredTypesConverter.Write(Utf8JsonWriter writer, object value, JsonSerializerOptions options)Writes the supplied value as JSON using its runtime type.Utf8JsonWriter, object, JsonSerializerOptionsReturns void, writes the runtime type, with a bare object represented as {}.
SystemTextJsonContentSerializer.DeserializeStreamAsync<T>(Stream stream, StreamingContentFormat format, CancellationToken cancellationToken = default)Selects the JSON array, JSON Lines or server-sent-events reader for a response stream.stream: Stream source; format: StreamingContentFormat framing; cancellationToken: CancellationToken used to cancel readsReturns IAsyncEnumerable<T?> using the selected framing. An unrecognized format uses the JSON-array reader.

Testing

Test a Refit client

Full description and examples.

Types: Refit.Testing.StubHttp.

API reference

Full description and examples.

APIDescriptionParametersReturns and behavior
StubHttpDeclarative HttpMessageHandler for Refit tests; stores route matchers and their replies, records requests, and supports one-shot, reusable and fallback routes.NoneHandler type implementing IEnumerable<RouteMatcher>.
StubHttp()Starts a handler with no expected routes.NoneCreates an empty route table using the default JSON content serializer.
StubHttp(NetworkBehavior behavior)Starts an empty handler and enables network-fault simulation.behavior: NetworkBehavior applied to each matched requestCreates an empty route table with the supplied behavior.
StubHttp.RequestsExposes requests received by the handler in arrival order.Get-only IReadOnlyList<HttpRequestMessage>Returns a live read-only view, including unmatched and failed requests.
StubHttp.BehaviorEnables, replaces or disables simulated network conditions.Nullable NetworkBehavior, get/set; default nullGets or sets behavior; null skips simulation.
StubHttp.Add(RouteMatcher route, StubResponse response)Adds a route and the reply returned when it matches; collection initializers call this method.route: RouteMatcher; response: StubResponseReturns void; rejects null arguments and tracks one-shot expectations.
StubHttp.ToSettings()Creates settings that route a Refit client through this handler.NoneReturns new RefitSettings whose handler factory returns this handler.
StubHttp.ToSettings(RefitSettings baseSettings)Reuses supplied settings and points them at this handler.baseSettings: RefitSettings to updateReturns the same settings after replacing its handler factory and adopting its serializer.
StubHttp.CreateClient<T>(string hostUrl)Creates a reflection-based Refit client using default settings.hostUrl: base addressReturns T from RestService.For<T>; carries runtime reflection/trimming requirements.
StubHttp.CreateClient<T>(string hostUrl, RefitSettings baseSettings)Creates a reflection-based client while retaining supplied serializer and URL settings.hostUrl: base address; baseSettings: RefitSettings to route through this handlerReturns T from RestService.For<T> after rewiring the supplied settings.
StubHttp.CreateGeneratedClient<T>(string hostUrl)Creates a source-generated Refit client using default settings.hostUrl: base addressReturns generated client T; throws InvalidOperationException when no generated implementation is registered.
StubHttp.CreateGeneratedClient<T>(string hostUrl, RefitSettings baseSettings)Creates a source-generated client while retaining supplied settings.hostUrl: base address; baseSettings: RefitSettings to route through this handlerReturns generated client T; throws InvalidOperationException when no generated implementation is registered.
StubHttp.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) (protected override)Records, matches and consumes an incoming request, applies network behavior, then builds its configured reply.request: HttpRequestMessage; cancellationToken: CancellationTokenReturns Task<HttpResponseMessage>; throws when no route matches or cancellation is requested.

Match outgoing requests

Full description and examples.

Types: Refit.Testing.Route, Refit.Testing.RouteMatcher.

Check queries, headers and bodies

Full description and examples.

PropertyRequired request behavior
MethodSame HTTP method. Null accepts any method.
QueryContains each decoded key/value pair. Extra pairs are allowed.
ExactQuerySame decoded pairs and count as the supplied encoded query, ignoring order. Omit the leading ?.
ExactQueryParamsSame decoded pairs and count as the supplied array, ignoring order.
HeadersContains each name/value pair in request or content headers. Names use HTTP header lookup. Values compare exactly. Multiple values join with ", ".
BodyExact body text. Missing content counts as an empty string.
FormDataContains each decoded form pair. Extra pairs are allowed. The media type is not checked.
WhereThe synchronous predicate returns true.
WhereAsyncThe asynchronous predicate returns true. It runs after Where passes.

API reference

Full description and examples.

APIDescriptionParameters or valueReturns and behavior
RouteProvides static factories for common request matchers.Static class; do not create an instance.Each factory returns a configured RouteMatcher.
Route.Any(string template)Matches a path regardless of its HTTP method.template: a relative or absolute path template; a complete {name} segment matches one path segment.Returns a RouteMatcher with no method restriction.
Route.Get(string template)Matches a GET request for a path.template: the relative or absolute path template to match.Returns a matcher whose method is GET.
Route.Post(string template)Matches a POST request for a path.template: the relative or absolute path template to match.Returns a matcher whose method is POST.
Route.Put(string template)Matches a PUT request for a path.template: the relative or absolute path template to match.Returns a matcher whose method is PUT.
Route.Delete(string template)Matches a DELETE request for a path.template: the relative or absolute path template to match.Returns a matcher whose method is DELETE.
Route.Patch(string template)Matches a PATCH request for a path.template: the relative or absolute path template to match.Returns a matcher whose method is PATCH.
Route.Head(string template)Matches a HEAD request for a path.template: the relative or absolute path template to match.Returns a matcher whose method is HEAD.
Route.For(HttpMethod method, string template)Matches a path for an HTTP method that has no convenience factory, such as OPTIONS.method: the HttpMethod to require; template: the relative or absolute path template to match.Returns a matcher for the supplied method and template.
Route.Fallback()Creates a catch-all route tried after every one-shot and reusable route.None.Returns a matcher with Template set to "*" and Fallback set to true; it may match repeatedly.
RouteMatcherDescribes the request that a route table entry accepts.Set Template and any init-only conditions in an object initializer.A configured matcher is paired with a Reply in StubHttp.
RouteMatcher()Creates a matcher for custom conditions.None.Returns a matcher with optional conditions unset. Set its required Template before it is added to a route table.
RouteMatcher.MethodRestricts a matcher to one HTTP method.Init-only HttpMethod?; null is the default.A non-null value must equal the request method. null accepts every method.
RouteMatcher.TemplateSupplies the path pattern every matcher needs.Required init-only string: a relative or absolute path, or "*" for every path.The handler matches this template against the request URI.
RouteMatcher.QueryRequires selected decoded query pairs.Init-only nullable array of (string Key, string Value) pairs to find.Every supplied pair must occur; the request may contain other pairs.
RouteMatcher.ExactQueryRequires the complete decoded query from encoded text.Init-only nullable string without a leading ?.Requires the same decoded pair count and members, ignoring order.
RouteMatcher.ExactQueryParamsRequires the complete decoded query from named pairs.Init-only nullable array of (string Key, string Value) pairs.Requires the same pair count and members, ignoring order.
RouteMatcher.HeadersRequires selected request or content headers.Init-only nullable array of (string Name, string Value) pairs.Every supplied header name and value must occur.
RouteMatcher.BodyRequires an exact text request body.Init-only nullable string containing the expected body.The request body must equal the value. Missing content is an empty string.
RouteMatcher.FormDataRequires selected decoded form fields.Init-only nullable array of (string Key, string Value) pairs to find in the body.Every supplied form pair must occur; extra pairs and the media type are ignored.
RouteMatcher.WhereAdds a synchronous check for details the built-in properties do not cover.Init-only nullable Func<HttpRequestMessage, bool>; its HttpRequestMessage argument is the request being matched.The route matches only when the predicate returns true.
RouteMatcher.WhereAsyncAdds an asynchronous check, such as one that reads the request body.Init-only nullable Func<HttpRequestMessage, Task<bool>>; use Task to return the result.The route matches only when the task completes with true, after Where passes.
RouteMatcher.ReusableMakes a route available for repeated background behavior.Init-only bool; default false.true allows repeated matches and excludes the route from VerifyAllCalled.
RouteMatcher.FallbackMakes a route the final match attempt.Init-only bool; default false.true gives the route fallback priority, allows repeated matches, and excludes it from VerifyAllCalled.
StubHttp.GetEnumerator() (explicit IEnumerable<RouteMatcher>)Lets you enumerate configured matchers as RouteMatcher values.None; cast StubHttp to IEnumerable<RouteMatcher> to call it.Returns an IEnumerator<RouteMatcher> over a snapshot of the route table.
StubHttp.GetEnumerator() (explicit IEnumerable)Lets non-generic code enumerate the configured matchers.None; cast StubHttp to IEnumerable to call it.Returns a non-generic IEnumerator over the same route snapshot.

Supply test replies

Full description and examples.

Types: Refit.Testing.Reply, Refit.Testing.StubResponse.

JSON, text and custom content

Full description and examples.

MethodBody and status
With<T>(body) / With<T>(body, status)Serialize the typed body with the adopted serializer. Status 200 or your supplied status.
Json(body) / Json(body, status)UTF-8 text with application/json. Status 200 or your supplied status. JSON validity is not checked.
Text(body) / Text(body, contentType)UTF-8 text with text/plain or your supplied media type. Status 200.
Status(statusCode)The supplied status with no explicit body.
Content(body)The exact HttpContent object, with status 200.
From(responder)Your lambda returns the complete response. Both sync and async overloads receive the request.

API reference

Full description and examples.

APIDescriptionParametersReturns and behavior
Reply.With<T>(T body)Creates a typed successful reply using the handler's serializer.body: generic type TReturns StubResponse that serializes the body with the handler serializer and uses HttpStatusCode.OK.
Reply.With<T>(T body, HttpStatusCode status)Creates a typed reply while choosing a non-default status.body: generic type T; status: HttpStatusCodeReturns StubResponse with serialized content and the supplied status.
Reply.Json(string body)Creates a successful reply from raw JSON text.body: string JSON textReturns StubResponse with UTF-8 application/json content and status HttpStatusCode.OK.
Reply.Json(string body, HttpStatusCode status)Creates a raw JSON reply with a caller-selected status.body: string JSON text; status: HttpStatusCodeReturns JSON StubResponse with the supplied status.
Reply.Text(string body)Creates a plain-text successful reply.body: string textReturns StubResponse with UTF-8 text/plain content and status HttpStatusCode.OK.
Reply.Text(string body, string contentType)Creates text content with a custom media type.body: string text; contentType: string media typeReturns UTF-8 text StubResponse with the supplied media type and status HttpStatusCode.OK.
Reply.Status(HttpStatusCode statusCode)Creates a bodyless reply for a chosen status code.statusCode: HttpStatusCode response statusReturns a StubResponse.
Reply.Content(HttpContent body)Reuses an explicit HTTP content instance as a reply body.body: HttpContent exact content instanceReturns StubResponse using that content and status HttpStatusCode.OK.
Reply.From(Func<HttpRequestMessage, HttpResponseMessage> responder)Uses a synchronous request-aware factory to build the whole reply.responder: Func<HttpRequestMessage, HttpResponseMessage> request-to-response functionReturns StubResponse whose responder supplies the complete HttpResponseMessage.
Reply.From(Func<HttpRequestMessage, Task<HttpResponseMessage>> responder)Uses an asynchronous request-aware factory to build the whole reply.responder: Func<HttpRequestMessage, Task<HttpResponseMessage>>, with Task<TResult> resultReturns StubResponse whose async responder supplies the complete HttpResponseMessage.
StubResponse()Creates an empty response description that you can configure with init properties.NoneCreates a StubResponse with HttpStatusCode.OK.
StubResponse.StatusChooses the status for a property-based reply.HttpStatusCode, init-only; default HttpStatusCode.OKSets the response status unless a responder supplies the complete response.
StubResponse.JsonSupplies the raw JSON alternative to a typed or explicit body.Nullable string, init-only; default nullSupplies raw JSON text.
StubResponse.TextSupplies a raw text alternative to a typed or explicit body.Nullable string, init-only; default nullSupplies raw text.
StubResponse.ContentTypeChooses the media type used when Text supplies the body.Nullable string, init-only; default nullSets media type for Text; it does not alter JSON or explicit content.
StubResponse.ContentSupplies an exact content object in preference to text and JSON.Nullable HttpContent, init-only; default nullSupplies exact content and takes precedence over JSON/text bodies.
StubResponse.ResponderSupplies the whole response through a synchronous callback.Nullable Func<HttpRequestMessage, HttpResponseMessage>, init-only; default nullSupplies a complete HttpResponseMessage synchronously.
StubResponse.ResponderAsyncSupplies the whole response through an asynchronous callback.Nullable Func<HttpRequestMessage, Task<HttpResponseMessage>>, with Task<TResult> result; init-only; default nullSupplies a complete HttpResponseMessage asynchronously and takes precedence over Responder.

Inspect requests and verify expectations

Full description and examples.

Verification API reference

Full description and examples.

OverloadDescriptionParametersReturns
VerifyAllCalled()Checks immediately that every one-shot route has been consumed.None.void; throws InvalidOperationException immediately if a one-shot expectation is missing.
VerifyAllCalledAsync()Waits for one-shot routes using the handler's default one-second timeout.None.Task: completes when all expectations are consumed, or faults with the missing-route error after one second.
VerifyAllCalledAsync(TimeSpan timeout)Waits for one-shot routes using a caller-selected timeout.TimeSpan timeout: maximum wait; zero checks immediately.Task: completes when expectations are consumed, or faults with the missing-route error after the timeout. See the completed-verification limitation below.
LastRequestBodyAsync<T>()Deserializes the most recently captured request body as T with the adopted serializer.None.Task<T?>: latest captured body deserialized as T, or default for absent or unbufferable content. Throws InvalidOperationException if there are no requests.
RequestBodyAsync<T>(int index)Deserializes the captured body at a recorded request position with the adopted serializer.int index: zero-based request position.Task<T?>: selected captured body deserialized as T, or default for absent or unbufferable content. Throws ArgumentOutOfRangeException for an invalid index.
PropertyTypeValue
RequestsIReadOnlyList<HttpRequestMessage>Get-only live list of recorded HttpRequestMessage objects in arrival order, including unmatched requests and failed sends.

Simulate network faults

Full description and examples.

Types: Refit.Testing.NetworkBehavior.

Defaults and calculation methods

Full description and examples.

OverloadDescriptionParametersReturns
NetworkBehavior()Creates deterministic fault simulation with the standard seed and defaults.None.A behavior with random seed 0 and the defaults below.
NetworkBehavior(int seed)Creates fault simulation whose random sequence starts from your chosen seed.int seed: random sequence seed.A behavior with the supplied seed and the defaults below. The same ordered calls repeat within a runtime.
NextDelay()Draws the delay that the next simulated request would use.None.TimeSpan: next varied delay. The multiplier is clamped at zero.
NextIsFailure()Draws whether the next simulation produces a connection failure.None.bool: next trial against FailurePercent.
NextIsError()Draws whether the next simulation produces an HTTP error response.None.bool: next trial against ErrorPercent.
CreateFailure()Builds the configured connection exception without throwing it.None.Exception: result of FailureFactory(). Creates the exception without throwing it.
CreateErrorResponse()Builds a disposable HTTP error reply from the configured status code.None.HttpResponseMessage: fresh response with the configured status and an empty text body. The caller must dispose it.
PropertyTypeDefault and behavior
DelayTimeSpanTwo seconds. Base delay for simulation.
Variancedouble0.4. Fraction above and below the delay. Zero fixes the delay.
FailurePercentdouble0.03. Connection-failure probability.
ErrorPercentdouble0. HTTP-error probability when no connection failure occurs.
ErrorStatusCodeHttpStatusCodeInternalServerError (500). Injected response status.
FailureFactoryFunc<Exception>Creates an HttpRequestException with message Refit.Testing simulated network failure.
StubHttp.BehaviorNetworkBehavior, nullableConstructor-supplied behavior, or null to disable simulation. See handler construction.

Test code that accepts a response

Full description and examples.

Types: Refit.Testing.StubApiResponse<T>.

Supply a consistent state

Full description and examples.

PropertyTypeDefault and what the test supplies
ContentT?default(T). Typed body for the scenario.
HasContentboolfalse. Whether the test promises non-null content.
IsSuccessfulWithContentboolfalse. Whether success and non-null content are both promised.
IsSuccessStatusCodeboolfalse. Whether the supplied status is 200–299.
IsSuccessfulboolfalse. Whether status succeeds and no error occurred.
IsReceivedboolfalse. Whether a reply arrived.
StatusCodeHttpStatusCode, nullablenull. Reply status for the scenario.
ReasonPhrasestring, nullablenull. Reply reason phrase.
VersionVersion, nullablenull. HTTP version.
HeadersHttpResponseHeaders, nullablenull. Reply header collection.
ContentHeadersHttpContentHeaders, nullablenull. Body header collection.
RequestMessageHttpRequestMessage, nullablenull. Associated request.
ErrorApiExceptionBase, nullablenull. Exception for a simulated failure.

Select an error kind

Full description and examples.

OverloadDescriptionParametersReturns
StubApiResponse<T>()Creates an independently configurable response wrapper for a test scenario.None. T is the body type.A stub with the defaults above.
HasRequestError(out ApiRequestException? error)Tests whether this stub represents a transport failure before a response arrived.ApiRequestException error: receives the request-phase error or null.bool: true exactly when Error is an ApiRequestException; the output is non-null on success.
HasResponseError(out ApiException? error)Tests whether this stub represents an HTTP or body-reading response failure.ApiException error: receives the response-phase error or null.bool: true exactly when Error is an ApiException, including ValidationApiException; the output is non-null on success.
Dispose()Satisfies the response-wrapper disposal contract without owning assigned resources.None.void; does not dispose any assigned resource.

Advanced APIs

Generated request helpers

Full description and examples.

Types: Refit.FormField<TBody>, Refit.GeneratedRequestRunner, Refit.UrlResolutionMode.

Path and formatting overloads

Full description and examples.

OverloadDescriptionParametersReturns
BuildRequestPath(string relativePathTemplate, bool allowUnmatchedParameter)Validates a parameterless route template before using it as a request path.string relativePathTemplate: route; bool allowUnmatchedParameter: whether unresolved placeholders are allowed.string: unchanged template, or throws for unresolved placeholders when the flag is false.
BuildRequestPath(string relativePathTemplate, bool allowUnmatchedParameter, ReadOnlySpan<((int StartIdx, int EndIdx) Range, string? Value)> uriParams)Replaces several path placeholders using default escaping.string template and bool unmatched flag; ReadOnlySpan uriParams: ordered placeholder ranges and replacement strings.string: path with escaped replacements and optional null segments removed.
BuildRequestPath(string relativePathTemplate, bool allowUnmatchedParameter, ReadOnlySpan<((int StartIdx, int EndIdx) Range, string? Value, bool PreEncoded)> uriParams)Replaces several placeholders while allowing selected values to bypass escaping.string template and bool unmatched flag; ReadOnlySpan uriParams: ordered ranges, values, and per-value encoding flags.string: path with replacements escaped unless their PreEncoded flag is true.
BuildRequestPath<T>(string relativePathTemplate, bool allowUnmatchedParameter, (int StartIdx, int EndIdx) range, T value)Replaces one placeholder with an invariant unformatted numeric value.string template; bool unmatched flag; tuple range: one placeholder; value: an ISpanFormattable. Requires T : ISpanFormattable.string: path with an invariant formatted value. Use this overload only for unformatted integers, as explained above.
BuildRequestPath<T>(string relativePathTemplate, bool allowUnmatchedParameter, (int StartIdx, int EndIdx) range, T value, string? format)Replaces one placeholder with an invariant value using a format string.string template; bool unmatched flag; tuple range: placeholder; ISpanFormattable value; string format: format or null. Requires T : ISpanFormattable.string: path with an escaped invariant formatted replacement.
BuildRelativeUri(HttpClient client, string relativePath, UrlResolutionMode urlResolution)Combines a route with the client base path under the selected resolution rule.HttpClient client: supplies the base path; string relativePath: route; UrlResolutionMode urlResolution: resolution rule.Uri: relative URI for HttpClient to resolve.
BuildRelativeUri(HttpClient client, string relativePath, UrlResolutionMode urlResolution, UriFormat queryUriFormat)Builds a relative URI and applies the legacy query rendering mode when relevant.HttpClient client; string relativePath; UrlResolutionMode urlResolution; UriFormat queryUriFormat: legacy path/query escaping rule.Uri: relative URI. RFC resolution ignores queryUriFormat.
RequireAbsoluteUrl(object? url)Rejects a URL value that is absent or not absolute.object url: a string or Uri with an absolute address.string: original URL text. Throws ArgumentException if it cannot be parsed as absolute. This does not enforce HTTP/HTTPS.
RoundTripEscapePath(string? value, RefitSettings settings, ICustomAttributeProvider attributeProvider, Type type)Formats and escapes a catch-all path without escaping its separators.string value: catch-all path or null; RefitSettings settings; ICustomAttributeProvider attributeProvider: formatting attributes; Type type: declared value type.string: formatted and escaped path sections with / separators retained.
FormatUrlParameter(RefitSettings settings, object? value, ICustomAttributeProvider attributeProvider, Type type)Formats one value through the registered or default URL formatter.RefitSettings settings; object value: value or null; ICustomAttributeProvider attributeProvider: attributes; Type type: declared type.string, nullable: result from the selected URL formatter.
FormatInvariant<T>(T value, string? format)Renders an IFormattable using invariant culture without URL escaping.value: an IFormattable; string format: format or null. Requires T : IFormattable.string: invariant formatted value without URL escaping.
BuildQueryKey(RefitSettings settings, string clrName, string? explicitName, string? prefixSegment)Builds the final query key from an alias or formatted CLR name and optional prefix.RefitSettings settings; string clrName: declared name; string explicitName: alias or null; string prefixSegment: prefix including delimiter, or null.string: explicit or formatted name with the prefix prepended.
UsesDefaultUrlParameterFormatting(RefitSettings settings)Checks whether URL values can use the built-in formatter fast path.RefitSettings settings: formatters to inspect.bool: whether inline URL formatting matches the pristine default formatter and the formatter map is empty.
UsesDefaultFormUrlEncodedParameterFormatting(RefitSettings settings)Checks whether form values use the exact built-in formatter type.RefitSettings settings: formatter to inspect.bool: whether the form formatter has the exact built-in default type.
UsesDefaultUrlParameterKeyFormatting(RefitSettings settings)Checks whether query keys use the exact built-in key formatter type.RefitSettings settings: formatter to inspect.bool: whether the key formatter has the exact built-in default type.
AddFormattedCollectionProperty(ref GeneratedQueryStringBuilder builder, RefitSettings settings, IEnumerable? values, string key, CollectionFormat collectionFormat, bool preEncoded, (Type ElementProviderType, ICustomAttributeProvider JoinedProvider, Type JoinedType) formatting)Formats and appends a collection-valued query property using the configured collection rule.GeneratedQueryStringBuilder builder: updated by reference; RefitSettings settings; IEnumerable values: collection or null; string key; CollectionFormat collectionFormat; bool preEncoded; tuple formatting: element Type, joined-value ICustomAttributeProvider, and joined Type.void; appends values using the two formatting passes described in query building. Null appends nothing.

Header and option overloads

Full description and examples.

OverloadDescriptionParametersReturns
SetHeader(HttpRequestMessage request, string name, string? value, bool validateHeaders)Replaces one request header and optionally validates its syntax.HttpRequestMessage request; string name: header name; string value: replacement or null; bool validateHeaders: whether to validate header syntax.void; replaces the header, or removes it for null.
AddHeaderCollection(HttpRequestMessage request, IDictionary<string, string>? headers, bool validateHeaders)Applies a collection of header replacements to the request.HttpRequestMessage request; IDictionary<string, string> headers: replacements or null; bool validateHeaders: whether to validate syntax.void; applies SetHeader to each entry. Null does nothing.
AddConfiguredRequestOptions(HttpRequestMessage request, RefitSettings settings, Type interfaceType)Copies configured request options and HTTP version settings onto a request.HttpRequestMessage request; RefitSettings settings: options and version rules; Type interfaceType: Refit interface.void; stores request options and interface type, plus HTTP version settings on modern .NET.
AddRequestProperty<TValue>(HttpRequestMessage request, string key, TValue value)Stores one typed request option for later request execution.HttpRequestMessage request; string key: option key; value: option value.void; sets a typed option, or a dictionary entry on .NET Framework.
SetRequestTimeout(HttpRequestMessage request, int timeoutMilliseconds)Records the per-request timeout for the send helper to apply.HttpRequestMessage request; int timeoutMilliseconds: timeout in milliseconds.void; stores a timeout for dispatch to apply.

Body helper overloads

Full description and examples.

OverloadDescriptionParametersReturns
CreateBodyContent<TBody>(RefitSettings settings, TBody body, BodySerializationMethod serializationMethod, bool streamBody)Serializes a request body according to the selected body mode, preserving supplied content and streams.RefitSettings settings; body: value to send; BodySerializationMethod serializationMethod; bool streamBody: whether serialized content streams.HttpContent: existing content, protected stream content, raw text, or serialized body as described above.
CreateJsonLinesBodyContent<TBody>(RefitSettings settings, TBody body)Creates newline-delimited JSON content from one value or an enumerable body.RefitSettings settings; body: one value or a sequence of values.HttpContent: JSON Lines content, or existing content/stream handling.
CreateStreamContent(Stream stream)Wraps a caller-owned stream without taking ownership of that stream.Stream stream: caller-owned body stream.HttpContent: wrapper that leaves the stream open when disposed.
CreateUrlEncodedBodyContent<TBody>(RefitSettings settings, TBody body)Converts a body to URL-encoded form content, with special handling for existing content, streams and strings.RefitSettings settings; body: form object, dictionary, string, content or stream.HttpContent: URL-encoded form or existing content/stream handling. Object flattening uses reflection.
CreateUrlEncodedBodyContent<TBody>(RefitSettings settings, TBody body, FormField<TBody>[] fields)Converts a body to URL-encoded form content using generated field descriptors when supported.RefitSettings settings; body: form value; fields: form descriptors with direct getters.HttpContent: form content using eligible descriptors, otherwise the reflection path described above.
CanUnrollForm(object? body)Checks whether a body can use the generated property-by-property form path.object body: candidate form value, or null.bool: true for non-null values other than strings, streams, HTTP content and dictionaries.
SerializeMultipartPart<T>(RefitSettings settings, T value, string fieldName)Serializes one multipart value with the configured content serializer.RefitSettings settings; value: one part; string fieldName: name used in an error.HttpContent: serialized part. Serializer failures become ArgumentException.
CompressBodyContent(HttpContent content, RefitSettings settings, RequestCompression compression, CompressionLevel level)Applies the resolved request compression setting to HTTP content.HttpContent content: input; RefitSettings settings: defaults/options; RequestCompression compression: coding; CompressionLevel level: effort for explicit coding.HttpContent: owning compression wrapper, or the same content when no coding applies.

Dispatch overloads

Full description and examples.

ParameterTypeValue
isApiResponsebooltrue when T is a supported response wrapper.
shouldDisposeResponsebooltrue for a fully consumed result. Use false when returning a live response owner.
bufferBodyboolWhether to buffer request content before sending.
OverloadDescriptionParametersReturns
SendVoidAsync(HttpClient client, HttpRequestMessage request, RefitSettings settings, bool bufferBody, CancellationToken cancellationToken)Sends a request whose successful result has no response body.HttpClient client; HttpRequestMessage request: message to send; RefitSettings settings; bool bufferBody: flag above; CancellationToken cancellationToken: request cancellation.Task: completion without a result. Disposes the request and response.
SendAsync<T, TBody>(HttpClient client, HttpRequestMessage request, RefitSettings settings, bool isApiResponse, bool shouldDisposeResponse, bool bufferBody, CancellationToken cancellationToken)Sends a request and processes its response as a deserialized value or API response wrapper.HttpClient client; HttpRequestMessage request; RefitSettings settings; three bool flags above; CancellationToken cancellationToken: request cancellation.Task<T?>: deserialized, raw, or wrapped result. Disposes the request. Response ownership follows the flag.
SendObservable<T, TBody>(HttpClient client, Func<HttpRequestMessage> requestFactory, RefitSettings settings, bool isApiResponse, bool shouldDisposeResponse, bool bufferBody, CancellationToken methodCancellationToken)Creates a cold observable that builds and sends a fresh request for each subscription.HttpClient client; Func<HttpRequestMessage> requestFactory: creates a fresh message per subscription; RefitSettings settings; three bool flags above; CancellationToken methodCancellationToken: caller cancellation.IObservable<T?>: sends one request per subscription and delivers its result or error. See observable replies.
StreamAsync<T>(HttpClient client, HttpRequestMessage request, RefitSettings settings, CancellationToken methodCancellationToken, CancellationToken cancellationToken = default)Sends a request and exposes the response body as an asynchronous stream.HttpClient client; HttpRequestMessage request: one message; RefitSettings settings; CancellationToken methodCancellationToken: caller token; CancellationToken cancellationToken: enumeration token, default non-cancelable.IAsyncEnumerable<T?>: one streaming response. Enumeration/disposal releases its request, response and stream.

Form field reference

Full description and examples.

OverloadDescriptionParametersReturns
FormField(Func<TBody, object?> getter, string clrName, string? explicitName, string? prefixSegment, string? format, CollectionFormat? collectionFormat, bool serializeNull)Creates a descriptor that reads and formats one URL-encoded form field.Func<TBody, object?> getter: reads a field; string clrName: declared name; nullable string arguments: explicit name, prefix with delimiter and value format; nullable CollectionFormat collectionFormat: override or settings default; bool serializeNull: whether null emits an empty field.A FormField<TBody> descriptor.
ResolveFieldName(IUrlParameterKeyFormatter urlParameterKeyFormatter)Resolves the final form key from the explicit name or configured key formatter.IUrlParameterKeyFormatter urlParameterKeyFormatter: formats ClrName when no explicit name is set.string, nullable: resolved name with the prefix prepended.
PropertyTypeValue
GetterFunc<TBody, object?>Reads the field value from a body instance.
ClrNamestringDeclared property name.
ExplicitNamestring, nullableAlias or serializer name; null uses the key formatter.
PrefixSegmentstring, nullablePrefix including delimiter; null adds none.
Formatstring, nullableValue format; null uses default formatting.
CollectionFormatCollectionFormat, nullableExplicit collection rule; null uses settings.
SerializeNullbooltrue emits an empty field for null; false omits it.
UrlResolutionMode valueNumeric valueMeaning
RefitLegacy0Prefix the base-address path and require a leading slash.
Rfc39861Use standard URI resolution. See URL settings.

Generated query builder

Full description and examples.

Types: Refit.GeneratedParameterAttributeProvider, Refit.GeneratedQueryStringBuilder, Refit.GeneratedSingleTypeParameterAttributeProvider.

Append a collection

Full description and examples.

FormatResult
MultiOne pair per non-null element; an empty collection emits nothing.
Csv or RefitParameterFormatterOne comma-joined value.
SsvOne value joined with spaces.
TsvOne value joined with tabs.
PipesOne value joined with vertical bars.
IndexedThis low-level helper joins with commas. Generated query-object code performs indexed expansion separately.

Query builder API reference

Full description and examples.

TypePurpose
GeneratedQueryStringBuilderA stack-only builder that appends an escaped query string to a relative request path without reflection.
GeneratedParameterAttributeProviderSupplies attributes from a dictionary when a generated parameter has more than one attribute type.
GeneratedSingleTypeParameterAttributeProviderSupplies one type's attributes without allocating a dictionary or flattening arrays.
OverloadDescriptionParametersReturns
GeneratedQueryStringBuilder(string relativePath)Starts query construction and detects an existing query marker.string relativePath: path with escaped dynamic segments and any template query.A builder that detects whether the path contains ?.
GeneratedQueryStringBuilder(string relativePath, bool hasQuery)Starts query construction using caller-known query state.string relativePath: escaped path; bool hasQuery: whether it contains ?.A builder that trusts the supplied query state.
Add(string name, string? value, bool preEncoded)Appends one ordinary query pair.string name: key; string value: value or null; bool preEncoded: whether both parts are encoded.void; appends a pair, or omits it for null. Empty values produce key=.
AddPreEscapedKey(string name, string? value, bool preEncoded)Appends a pair whose key has already been escaped.string name: escaped key; string value: value or null; bool preEncoded: whether the value is encoded.void; appends the key verbatim and escapes the value unless preEncoded is true. Null omits the pair.
AddFormatted<T>(string name, T value, string? format, bool preEncoded)Formats a value invariantly before appending an ordinary pair.string name: key; ISpanFormattable value: value to format; string format: format or null; bool preEncoded: whether the key and formatted value are encoded.void; formats with invariant culture and appends the pair.
AddFormattedPreEscapedKey<T>(string name, T value, string? format, bool preEncoded)Formats a value for a key that has already been escaped.string name: escaped key; ISpanFormattable value: value to format; string format: format or null; bool preEncoded: whether the formatted value is encoded.void; appends the key verbatim and formats the value with invariant culture.
AddFlag(string? name, bool preEncoded)Appends a valueless query flag.string name: flag text or null; bool preEncoded: whether it is encoded.void; appends a key without =, or omits a null flag.
BeginCollection(string name, CollectionFormat collectionFormat, bool preEncoded)Opens a collection whose values will be appended next.string name: key; CollectionFormat collectionFormat: join/repeat rule; bool preEncoded: whether the key and values are encoded.void; opens a collection. Finish the preceding collection first.
AddCollectionValue(string? value)Adds one raw value to the open collection.string value: next value, or null.void; adds a value to the open collection. Null is omitted for Multi and adds an empty position for joined formats.
AddCollectionValueFormatted<T>(T value)Formats and adds one value to the open collection.ISpanFormattable value: next value to format.void; formats with invariant culture and no format string, then adds it to the open collection.
EndCollection()Closes the open collection and writes its joined value when needed.None.void; finishes the open collection and writes any joined value.
Build()Finalizes the path and releases builder storage.None.string: the completed relative path and query. Releases pooled storage. Treat this as the final operation.

Attribute provider API reference

Full description and examples.

OverloadDescriptionParametersReturns
GeneratedParameterAttributeProvider(Dictionary<Type, object[]> attributes)Creates an attribute provider for parameters with several attribute types.Dictionary<Type, object[]> attributes: each Type and its array of attribute objects.A provider for several attribute types.
GeneratedParameterAttributeProvider.GetCustomAttributes(bool inherit)Returns every configured attribute as one shared array.bool inherit: ignored.object[]: cached array of all configured attributes. Treat the returned array as read-only.
GeneratedParameterAttributeProvider.GetCustomAttributes(Type attributeType, bool inherit)Returns attributes for one exact configured type.Type attributeType: exact type to find; bool inherit: ignored.object[]: the stored array, or an empty array when the key is absent.
GeneratedParameterAttributeProvider.IsDefined(Type attributeType, bool inherit)Checks whether an exact attribute type has an entry.Type attributeType: exact type to find; bool inherit: ignored.bool: whether the dictionary contains the key, even if its array is empty.
GeneratedSingleTypeParameterAttributeProvider(Type type, object[] attributes)Creates an attribute provider optimized for one attribute type.Type type: shared attribute type; object[] attributes: attribute objects of that type.A provider for one attribute type.
GeneratedSingleTypeParameterAttributeProvider.GetCustomAttributes(bool inherit)Returns the provider's configured attribute array.bool inherit: ignored.object[]: the supplied array. Treat it as read-only.
GeneratedSingleTypeParameterAttributeProvider.GetCustomAttributes(Type attributeType, bool inherit)Returns attributes only when the requested type matches.Type attributeType: exact type to find; bool inherit: ignored.object[]: the supplied array for the configured type, otherwise an empty array.
GeneratedSingleTypeParameterAttributeProvider.IsDefined(Type attributeType, bool inherit)Checks whether the requested type matches the configured type.Type attributeType: exact type to find; bool inherit: ignored.bool: whether the type equals the configured type, even if its array is empty.
FieldDescriptionTypeValue
GeneratedParameterAttributeProvider.EmptyReuses one provider for parameters that declare no attributes.GeneratedParameterAttributeProviderShared static readonly provider with no attributes.
OverloadDescriptionParametersReturns
GeneratedRequestRunner.FormatUrlParameter(RefitSettings settings, object? value, ICustomAttributeProvider attributeProvider, Type type)Formats one query value through the configured URL formatter.RefitSettings settings: formatter configuration; object value: value or null; ICustomAttributeProvider attributeProvider: attributes for formatting; Type type: declared value type.string, nullable: result from the selected URL formatter.

Method metadata and client names

Full description and examples.

Types: Refit.ParameterType, Refit.RestMethodInfo, Refit.RestMethodParameterInfo, Refit.RestMethodParameterProperty, Refit.UniqueName.

Method record reference

Full description and examples.

OverloadDescriptionParametersReturns
RestMethodInfo(string Name, Type HostingType, MethodInfo MethodInfo, string RelativePath, Type ReturnType)Packages the reflected details that identify one Refit method.string Name: method name; Type HostingType: declaring interface; MethodInfo MethodInfo: reflected method; string RelativePath: route template; Type ReturnType: declared result type.A RestMethodInfo containing the supplied metadata.
Deconstruct(out string Name, out Type HostingType, out MethodInfo MethodInfo, out string RelativePath, out Type ReturnType)Splits the record into its positional values for deconstruction syntax.The five out arguments receive the corresponding properties below, in constructor order.void; copies the stored values to the arguments.
Equals(RestMethodInfo? other)Compares this record with another method record.other: another method record, or null.bool: true when all five properties are equal; false for null.
Equals(object? obj)Compares this record with an arbitrary object of the same record type.object obj: any object, or null.bool: true only for a RestMethodInfo with equal properties.
operator ==(RestMethodInfo? left, RestMethodInfo? right)Tests two records for value equality.left, right: records to compare. Both may be null.bool: true for equal records or two nulls.
operator !=(RestMethodInfo? left, RestMethodInfo? right)Tests two records for unequal values.left, right: records to compare. Both may be null.bool: the opposite of ==.
GetHashCode()Produces a hash for use in hash-based collections.None.int: a hash based on the stored values. Equal records have equal hashes.
ToString()Renders the record and its values for diagnostics.None.string: the record name and its property names and values.
<Clone>$() (compiler member used by with)Makes the shallow copy used by a C# with expression.None. Use a with expression in C# rather than calling this metadata name.A shallow RestMethodInfo copy. The reflected objects are shared with the original.
PropertyTypeValue and access
NamestringMethod name supplied to the constructor; get; init;.
HostingTypeTypeDeclaring interface supplied to the constructor; get; init;.
MethodInfoMethodInfoReflected method supplied to the constructor; get; init;.
RelativePathstringRoute template supplied to the constructor; get; init;.
ReturnTypeTypeDeclared result type supplied to the constructor; get; init;.

Parameter metadata reference

Full description and examples.

OverloadDescriptionParametersReturns
RestMethodParameterInfo(string name, ParameterInfo parameterInfo)Describes a route parameter by its binding name.string name: route parameter name; ParameterInfo parameterInfo: reflected parameter.A named parameter description with IsObjectPropertyParameter = false.
RestMethodParameterInfo(bool isObjectPropertyParameter, ParameterInfo parameterInfo)Describes a parameter whose properties supply route values.bool isObjectPropertyParameter: whether the binding reads object properties; ParameterInfo parameterInfo: reflected parameter.A parameter description with the supplied flag and Name = null.
RestMethodParameterProperty(string name, PropertyInfo propertyInfo)Describes one direct property used in route binding.string name: route binding name; PropertyInfo propertyInfo: property to read.A property description with a one-element navigation chain.
RestMethodParameterProperty(string name, IReadOnlyList<PropertyInfo> propertyChain)Describes a nested property walk used in route binding.string name: route binding name; IReadOnlyList<PropertyInfo> propertyChain: non-empty chain of PropertyInfo objects in navigation order.A property description that retains the list and uses its final element as PropertyInfo.
PropertyTypeValue and access
RestMethodParameterInfo.Namestring, nullableName supplied to the named constructor, or null for the flag constructor; get; set;.
RestMethodParameterInfo.ParameterInfoParameterInfoReflected parameter supplied to either constructor; get; set;.
RestMethodParameterInfo.IsObjectPropertyParameterboolWhether the binding reads object properties; defaults to false in the named constructor; get; set;.
RestMethodParameterInfo.ParameterPropertiesList<RestMethodParameterProperty>Starts empty. The list can be replaced during initialization and its contents can be changed later; get; init;.
RestMethodParameterInfo.TypeParameterTypeStarts as Normal; get; set;. See the values below.
RestMethodParameterProperty.NamestringBinding name supplied to either constructor; get; set;.
RestMethodParameterProperty.PropertyInfoPropertyInfoFinal property to read; get; set;. Assigning it does not change PropertyChain.
RestMethodParameterProperty.PropertyChainIReadOnlyList<PropertyInfo>Ordered navigation chain; get; set;. Assigning it does not change PropertyInfo.
ParameterType valueNumeric valueMeaning
Normal0Ordinary route value escaping.
RoundTripping1Catch-all path handling that retains / separators.

Client name overloads

Full description and examples.

OverloadDescriptionParametersReturns
UniqueName.ForType<T>()Reconstructs the generated implementation name for interface T.None. T selects the interface.string: generated implementation name, including assembly identity.
UniqueName.ForType<T>(object? serviceKey)Adds a service-key suffix when naming interface T.object serviceKey: key used for registration, or null.string: generated name with a service-key suffix, unless the key is null or an empty string.
UniqueName.ForType(Type refitInterfaceType)Reconstructs a generated implementation name from a runtime interface type.Type refitInterfaceType: interface to name.string: the same name as the generic overload for that interface.
UniqueName.ForType(Type refitInterfaceType, object? serviceKey)Reconstructs a runtime interface name with an optional service-key suffix.Type refitInterfaceType: interface to name; object serviceKey: registration key, or null.string: name with the same service-key rules as the generic overload.