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.
| Overload | Description | Parameters | Returns |
|---|---|---|---|
RestService | Static 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>(HttpClient client, JsonSerializerContext context) | Resolves the registered generated implementation for T and reads and writes JSON with the context's own options. It never builds reflected requests and never uses reflection-based JSON. | HttpClient client: non-null client; JsonSerializerContext context: the generated context. | T: generated implementation. Throws InvalidOperationException when no generated implementation is available. A request or reply type that the context does not list throws NotSupportedException. .NET 8 and later. |
ForGenerated<T>(HttpClient client, JsonSerializerContext context, bool allowReflectionFallback) | Resolves the generated implementation for T with the context's own options, optionally with a reflection fallback. | client; context; bool allowReflectionFallback: true lets a type the context does not list use reflection-based JSON. Reflection is not trim or Native AOT safe. | T: generated implementation. .NET 8 and later. |
ForGenerated<T>(HttpClient client, JsonSerializerContext context, RefitSettings settings) | Resolves the generated implementation for T, keeps the settings' serializer options and adds the context. | client; context; RefitSettings settings: non-null settings whose serializer is a SystemTextJsonContentSerializer. | T: generated implementation. Sets settings.ContentSerializer to a serializer built on a copy of its options plus the context. Throws InvalidOperationException when the settings use another serializer. .NET 8 and later. |
ForGenerated<T>(HttpClient client, JsonSerializerContext context, RefitSettings settings, bool allowReflectionFallback) | Resolves the generated implementation for T, keeps the settings' serializer options and adds the context, optionally with a reflection fallback. | client; context; settings; allowReflectionFallback: true lets a type no resolver lists use reflection-based JSON. Not trim or Native AOT safe. | T: generated implementation. .NET 8 and later. |
ForGenerated<T>(string hostUrl, JsonSerializerContext context) | Creates an HTTP client, then resolves the generated implementation for T on the context's own options with reflection-based JSON off. | string hostUrl: non-null, non-whitespace base address; context. | T: generated implementation; if T inherits IDisposable, disposing it also disposes the created client. .NET 8 and later. |
ForGenerated<T>(string hostUrl, JsonSerializerContext context, bool allowReflectionFallback) | Creates an HTTP client, then resolves the generated implementation for T on the context's own options, optionally with a reflection fallback. | hostUrl; context; allowReflectionFallback. | T: generated implementation. .NET 8 and later. |
ForGenerated<T>(string hostUrl, JsonSerializerContext context, RefitSettings settings) | Creates an HTTP client with the supplied settings, keeps their serializer options and adds the context. | hostUrl; context; settings: non-null settings whose serializer is a SystemTextJsonContentSerializer. | T: generated implementation. Sets settings.ContentSerializer to the composed serializer. .NET 8 and later. |
ForGenerated<T>(string hostUrl, JsonSerializerContext context, RefitSettings settings, bool allowReflectionFallback) | Creates an HTTP client with the supplied settings, keeps their serializer options and adds the context, optionally with a reflection fallback. | hostUrl; context; settings; allowReflectionFallback. | T: generated implementation. .NET 8 and later. |
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.
| Declaration | Description | Parameters and defaults | Return/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.AddRefitGeneratedClient<T>(JsonSerializerContext context) | Registers the generated implementation of T on a JSON context's own options, with reflection-based JSON off, and Refit's derived HTTP client name. | T : class; JsonSerializerContext context: the generated context. | IHttpClientBuilder: registers generated-only T. A type the context does not list throws NotSupportedException when a call runs. .NET 8 and later. |
IServiceCollection.AddRefitGeneratedClient<T>(JsonSerializerContext context, bool allowReflectionFallback) | Registers the generated implementation of T on the context's own options, optionally with a reflection fallback. | T : class; context; bool allowReflectionFallback: true lets a type the context does not list use reflection-based JSON. Not trim or Native AOT safe. | IHttpClientBuilder: registers generated-only T. .NET 8 and later. |
IServiceCollection.AddRefitGeneratedClient<T>(JsonSerializerContext context, Func<IServiceProvider, RefitSettings?>? settingsAction) | Registers the generated implementation of T, keeps the settings that settingsAction returns and adds the context. | T : class; context; settingsAction: nullable provider settings factory. A null result uses the context's own options. | IHttpClientBuilder: registers generated-only T. Refit sets the composed serializer on the settings the factory returns. .NET 8 and later. |
IServiceCollection.AddRefitGeneratedClient<T>(JsonSerializerContext context, Func<IServiceProvider, RefitSettings?>? settingsAction, string? httpClientName) | Registers the generated implementation of T as above under the supplied HTTP client name. | T : class; context; settingsAction; httpClientName: nullable underlying client name. | IHttpClientBuilder: registers generated-only T under that HTTP client name. .NET 8 and later. |
IServiceCollection.AddRefitGeneratedClient<T>(JsonSerializerContext context, Func<IServiceProvider, RefitSettings?>? settingsAction, string? httpClientName, bool allowReflectionFallback) | Registers the generated implementation of T as above, optionally with a reflection fallback. | T : class; context; settingsAction; httpClientName; allowReflectionFallback: true lets a type no resolver lists use reflection-based JSON. Not trim or Native AOT safe. | IHttpClientBuilder: registers generated-only T. .NET 8 and later. |
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. |
IServiceCollection.AddKeyedRefitGeneratedClient<T>(object? serviceKey, JsonSerializerContext context) | Registers the generated implementation of T under the required non-null service key on a JSON context's own options, with reflection-based JSON off. | T : class; serviceKey: non-null DI key; context: the generated context. | IHttpClientBuilder: registers keyed generated-only T. .NET 8 and later. |
IServiceCollection.AddKeyedRefitGeneratedClient<T>(object? serviceKey, JsonSerializerContext context, Func<IServiceProvider, RefitSettings?>? settingsAction) | Registers the generated implementation of T under the key, keeps the settings that settingsAction returns and adds the context. | T : class; serviceKey; context; settingsAction: nullable provider settings factory. A null result uses the context's own options. | IHttpClientBuilder: registers keyed generated-only T. .NET 8 and later. |
IServiceCollection.AddKeyedRefitGeneratedClient<T>(object? serviceKey, JsonSerializerContext context, Func<IServiceProvider, RefitSettings?>? settingsAction, string? httpClientName, bool allowReflectionFallback) | Registers the generated implementation of T under the key as above, with an HTTP client name and an optional reflection fallback. | T : class; serviceKey; context; settingsAction; httpClientName; allowReflectionFallback: true lets a type no resolver lists use reflection-based JSON. Not trim or Native AOT safe. | IHttpClientBuilder: registers keyed generated-only T. .NET 8 and later. |
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>.Settings | Exposes 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.Settings | Exposes the nullable RefitSettings reference from a SettingsFor<T> instance without exposing its interface type. | None. | RefitSettings?: the settings reference stored by that holder. |
| Type | Purpose |
|---|---|
Refit.HttpClientFactoryExtensions | Static extension class for service-collection and existing-builder registration methods. |
Refit.ISettingsFor | Interface 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.
| Member | Description | Parameters | Returns or value |
|---|---|---|---|
RefitSettings | Holds 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. |
RefitSettings.ForJsonContext(JsonSerializerContext context) | Creates settings that run on a context's own options, with reflection-based JSON off. | JsonSerializerContext context: the generated context. | New RefitSettings whose serializer is SystemTextJsonContentSerializer.ForContext(context). A type the context does not list throws NotSupportedException. .NET 8 and later. |
RefitSettings.ForJsonContext(JsonSerializerContext context, bool allowReflectionFallback) | Creates settings that run on a context's own options, optionally with a reflection fallback. | context; bool allowReflectionFallback: true lets a type the context does not list use reflection-based JSON. Not trim or Native AOT safe. | New RefitSettings. .NET 8 and later. |
UseJsonContext(JsonSerializerContext context) | Adds a context to these settings' System.Text.Json serializer, with reflection-based JSON off. | context: the generated context that supplies metadata for the types it lists. | These settings. Only ContentSerializer changes, to a serializer built on a copy of the current options plus the context. The naming policy, converters and resolvers stay in place. Throws InvalidOperationException when the serializer is not a SystemTextJsonContentSerializer. .NET 8 and later. |
UseJsonContext(JsonSerializerContext context, bool allowReflectionFallback) | Adds a context to these settings' System.Text.Json serializer, optionally with a reflection fallback. | context; allowReflectionFallback: true lets a type no resolver lists use reflection-based JSON. Not trim or Native AOT safe. | These settings. Throws InvalidOperationException when the serializer is not a SystemTextJsonContentSerializer. .NET 8 and later. |
AuthorizationHeaderValueGetter | Supplies 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. |
HttpMessageHandlerFactory | Supplies 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. |
ExceptionFactory | Maps unsuccessful HTTP responses to exceptions. | Func<HttpResponseMessage, ValueTask<Exception?>>. | Exception factory; default creates Refit API exceptions. A null result suppresses the HTTP error. |
DeserializationExceptionFactory | Maps response-body deserialization failures to exceptions. | Func<HttpResponseMessage, Exception, ValueTask<Exception?>> or null. | Deserialization exception factory; default null. A null result suppresses the error. |
ContentSerializer | Serializes request bodies and deserializes response bodies. | IHttpContentSerializer. | Body/reply serializer; default SystemTextJsonContentSerializer. |
ReturnTypeAdapters | Registers 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. |
UrlParameterKeyFormatter | Formats parameter names used in route, query, and form data. | IUrlParameterKeyFormatter. | URL/form key formatter; default DefaultUrlParameterKeyFormatter. |
HonorContentSerializerPropertyNamesInQuery | Chooses whether flattened query names follow serializer property names. | bool. | true makes flattened query keys honor serializer names; default true. AliasAs wins in either mode. |
UrlParameterFormatter | Formats parameter values inserted into URLs. | IUrlParameterFormatter. | Path/query value formatter; default DefaultUrlParameterFormatter. |
UrlParameterFormatterMap | Selects 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. |
FormUrlEncodedParameterFormatter | Formats values written into form-url-encoded request bodies. | IFormUrlEncodedParameterFormatter. | Form value formatter; default DefaultFormUrlEncodedParameterFormatter. |
CollectionFormat | Selects how collection values become repeated or joined URL parameters. | CollectionFormat. | Collection rendering mode; default RefitParameterFormatter. |
Buffered | Chooses whether request content is buffered before the HTTP send. | bool. | Buffer request content before sending; default false. |
CaptureRequestContent | Captures 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. |
CaptureMethodArguments | Stores boxed interface-call arguments in the request options for a handler to inspect. | bool. | Retain an object?[] for the request lifetime; default false. |
MaxExceptionContentLength | Limits the response-body characters captured while building an API exception. | int? characters. | Error-body capture limit; default null (unbounded). |
ExceptionRedactor | Scrubs sensitive data from an ApiExceptionBase before Refit returns it. | Action<ApiExceptionBase> or null. | Exception scrubbing hook; default null. |
AllowUnmatchedRouteParameters | Allows route placeholders without matching method parameters. | bool. | Leaves unmatched {token} text for later rewriting when true; default false. |
ValidateHeaders | Enables framework validation when Refit applies declared headers. | bool. | Use framework header parsing; default false. Invalid values throw FormatException when a request is built. |
UrlResolution | Selects how relative request paths resolve against HttpClient.BaseAddress. | UrlResolutionMode. | Base-address resolution mode; default RefitLegacy. |
RequestBodySerialization | Selects how Refit creates JSON request-body content. | RequestBodySerializationMode. | JSON body serialization mode; default Default. Buffered and Streamed require ISynchronousContentSerializer. |
RequestCompression | Selects the content encoding applied to every request body. | RequestCompression. | Request-body coding; default None. A [Body] coding overrides this setting. |
RequestCompressionLevel | Sets the compression effort for compressed request bodies. | CompressionLevel. | Compression effort; default Optimal. |
RequestCompressionOptions | Provides 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. |
HttpRequestMessageOptions | Copies 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. |
TransportExceptionFactory | Maps 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. |
Version | Sets the HTTP version requested on generated requests. | Version (.NET 6+). | Requested HTTP version; default HTTP/1.1. |
VersionPolicy | Sets the policy used when negotiating the requested HTTP version. | HttpVersionPolicy (.NET 6+). | Version negotiation policy; default RequestVersionOrLower. |
Enum | Value | Meaning |
|---|---|---|
CollectionFormat | RefitParameterFormatter (0) | Use the configured value formatter. |
CollectionFormat | Csv (1), Ssv (2), Tsv (3), Pipes (4) | Comma, space, tab, or pipe separated values. |
CollectionFormat | Multi (5) | Repeat the parameter for each value. |
CollectionFormat | Indexed (6) | Expand object elements with indexed keys. |
RequestBodySerializationMode | Default (0) | Normal asynchronous serialization. |
RequestBodySerializationMode | Buffered (1) | Synchronous serialization into buffered content. |
RequestBodySerializationMode | Streamed (2) | Synchronous serialization to the request stream. |
RequestCompression | Default (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. |
CompressionLevel | Optimal (0), Fastest (1), NoCompression (2), SmallestSize (3) | Compression effort choices used by RequestCompressionLevel. |
UrlResolutionMode | RefitLegacy (0), Rfc3986 (1) | Legacy base-path prepending or RFC 3986 URI resolution. |
System.Net.Http.HttpVersionPolicy | RequestVersionOrLower (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.
| Declaration | Description | Parameters and defaults | Return/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.Settings | Exposes 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. |
IRequestBuilder | Defines 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. |
RequestBuilder | Provides 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.
| Attribute | HTTP method | Common use |
|---|---|---|
[Get(path)] | GET | Read a resource. |
[Post(path)] | POST | Submit data or create a resource. |
[Put(path)] | PUT | Replace a resource. |
[Patch(path)] | PATCH | Change part of a resource. |
[Delete(path)] | DELETE | Remove a resource. |
[Head(path)] | HEAD | Read reply headers without a reply body. |
[Options(path)] | OPTIONS | Ask what operations a service accepts. |
Route attribute reference¶
Full description and examples.
| Member | Description | Parameters | Returns or value |
|---|---|---|---|
HttpMethodAttribute | Base 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.Method | Identifies the HTTP verb represented by the attribute. | None. Abstract getter. | HttpMethod for the operation. |
HttpMethodAttribute.Path | Holds 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. |
DeleteAttribute | Attribute 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.Method | Supplies the HTTP method for a DELETE route. | None. | HttpMethod.Delete. |
GetAttribute | Attribute 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.Method | Supplies the HTTP method for a GET route. | None. | HttpMethod.Get. |
HeadAttribute | Attribute 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.Method | Supplies the HTTP method for a HEAD route. | None. | HttpMethod.Head. |
OptionsAttribute | Attribute 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.Method | Supplies the HTTP method for an OPTIONS route. | None. | HttpMethod whose method name is OPTIONS. |
PatchAttribute | Attribute 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.Method | Supplies a custom HttpMethod whose name is PATCH. | None. | HTTP method named PATCH. |
PathPrefixAttribute | Attribute 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.Prefix | Exposes the prefix supplied to the constructor. | None. Read-only. | string route prefix. |
PostAttribute | Attribute 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.Method | Supplies the HTTP method for a POST route. | None. | HttpMethod.Post. |
PutAttribute | Attribute 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.Method | Supplies the HTTP method for a PUT route. | None. | HttpMethod.Put. |
UrlAttribute | Attribute 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.
CollectionFormat | Shape for two string values |
|---|---|
Csv | tags=math%2Ccode |
Ssv | tags=math%20code |
Tsv | tags=math%09code |
Pipes | tags=math%7Ccode |
Multi | tags=math&tags=code |
Indexed | Object properties such as people[0].Id=1&people[1].Id=2. |
RefitParameterFormatter | Uses the configured formatter. The default query formatter joins values with commas. |
Query attribute choices¶
Full description and examples.
| Attribute or property | Use |
|---|---|
AliasAs(name) / Name | Sets an explicit parameter or property name. |
Query() | Keeps the default delimiter and the configured collection format. |
Query(delimiter) / Delimiter | Chooses the text between nested names. The default is .. |
Query(delimiter, prefix) / Prefix | Adds a name before flattened properties. |
Query(delimiter, prefix, format) / Format | Also supplies a value format string. |
Query(collectionFormat) / CollectionFormat | Selects a collection format for this argument. |
Query.IsCollectionFormatSpecified | Tells custom code whether the attribute explicitly chose a collection format. |
Query.TreatAsString | Uses the object's ToString() result instead of flattening its properties. |
Query.SerializeNull | Sends a null property as an empty value. |
QueryName() | Sends valueless flags. |
Encoded() | Keeps caller-escaped text. |
QueryUriFormat(uriFormat) / UriFormat | Sets the final path and query rendering mode. |
| Member | Description | Parameters | Returns or value |
|---|---|---|---|
CollectionFormat | Selects how a collection becomes query or form text. | None. | enum with the values listed above. |
CollectionFormat.RefitParameterFormatter | Delegates collection rendering to the configured URL or form formatter. | None. | int value 0; the default enum value. |
CollectionFormat.Csv | Joins values with a comma. | None. | int value 1. |
CollectionFormat.Ssv | Joins values with a space. | None. | int value 2. |
CollectionFormat.Tsv | Joins values with a tab. | None. | int value 3. |
CollectionFormat.Pipes | Joins values with a pipe character. | None. | int value 4. |
CollectionFormat.Multi | Emits one key-value pair for each collection value. | None. | int value 5. |
CollectionFormat.Indexed | Expands each object element under an indexed key such as items[0].Name. | None. | int value 6; scalar elements use comma-separated values. |
AliasAsAttribute | An 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.Name | Returns the alias supplied to the constructor. | None. Read-only. | string wire name. |
EncodedAttribute | An 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. |
QueryAttribute | An 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.CollectionFormat | Gets 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.Delimiter | Returns the separator that joins the prefix and flattened property name. | None. Read-only. | string, default ".". |
QueryAttribute.Format | Gets or sets the format string for a scalar query value. | None. | string or null; default null. |
QueryAttribute.IsCollectionFormatSpecified | Reports whether code assigned CollectionFormat, including through the collection-format constructor. | None. Read-only. | bool, default false. |
QueryAttribute.Prefix | Returns the name prepended to each flattened property. | None. Read-only. | string or null; default null. |
QueryAttribute.SerializeNull | Controls whether a null property is written as an empty value instead of omitted. | None. | bool, default false. |
QueryAttribute.TreatAsString | Controls whether Refit uses an object's ToString() result instead of flattening its properties. | None. | bool, default false. |
QueryNameAttribute | An 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. |
QueryUriFormatAttribute | An 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.UriFormat | Returns 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 formatter | Format("PageSize") | Settings shortcut |
|---|---|---|
DefaultUrlParameterKeyFormatter | PageSize | The default settings. |
CamelCaseUrlParameterKeyFormatter | pageSize | RefitSettings.CamelCase() |
SnakeCaseUrlParameterKeyFormatter | page_size | RefitSettings.SnakeCase() |
KebabCaseUrlParameterKeyFormatter | page-size | RefitSettings.KebabCase() |
API reference¶
Full description and examples.
| API | Description | Parameters | Returns 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 Type | Returns 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 null | Returns 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 key | Returns the formatted string key. |
DefaultUrlParameterKeyFormatter() | Creates the default key formatter. | None | Creates 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 key | Returns the same key. |
CamelCaseUrlParameterKeyFormatter() | Creates a key formatter that converts leading uppercase letters to camelCase. | None | Creates 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 key | Returns the camelCase string key. |
SnakeCaseUrlParameterKeyFormatter() | Creates a key formatter that separates words with underscores. | None | Creates a snake_case key formatter. |
SnakeCaseUrlParameterKeyFormatter.Format(string key) | Converts a key to snake_case. | key: string key | Returns the snake_case string key. |
KebabCaseUrlParameterKeyFormatter() | Creates a key formatter that separates words with hyphens. | None | Creates a kebab-case key formatter. |
KebabCaseUrlParameterKeyFormatter.Format(string key) | Converts a key to kebab-case. | key: string key | Returns the kebab-case string key. |
DefaultFormUrlEncodedParameterFormatter() | Creates the default form-url-encoded value formatter. | None | Creates 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 null | Returns invariant-culture string text, uses an EnumMember value when available, and returns null for a null value. |
DefaultUrlParameterFormatter() | Creates the default URL value formatter. | None | Creates 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 type | Returns 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 type | Returns 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 Type | Returns 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.
| API | Description | Parameters | Returns 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. |
QueryConverterAttribute | Marks 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.ConverterType | Identifies 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 property | Use |
|---|---|
Headers(params string[] headers) / Headers | Shared interface or method headers. |
Header(string header) / Header | One header value from a method argument. |
HeaderCollection() | A header dictionary from a method argument. |
Authorize(string scheme = "Bearer") / Scheme | An authorization token from a method argument. |
RefitSettings.AuthorizationHeaderValueGetter | Obtains a missing token before a declared authorized request is sent. |
RefitSettings.ValidateHeaders | Chooses whether .NET validates header values. |
Header attribute reference¶
Full description and examples.
| Member | Description | Parameters | Returns 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.Scheme | Gets 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.Header | Gets 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.Headers | Gets 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 property | Value and use |
|---|---|
InterfaceType | The top-level interface type for the call. |
MethodName | The declared method name, such as BuildAsync. |
RelativePathTemplate | The unfilled route, such as /people/{id}. Use this stable name for request metrics. |
RestMethodInfo | Reflected method details when the request-building path supplies them. Generated requests avoid this reflection. |
MethodArguments | The argument array when CaptureMethodArguments is true. |
RequestContent | The captured body text when CaptureRequestContent is true. |
Request context reference¶
Full description and examples.
| Member | Description | Parameters | Returns or value |
|---|---|---|---|
PropertyAttribute | Marks 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.Key | Gets 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. |
HttpRequestMessageOptions | Provides 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.InterfaceType | Identifies 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.RestMethodInfo | Identifies the option that stores reflected method details when the reflection request builder supplies them. | None. Static read-only property. | string "Refit.RestMethodInfo". |
HttpRequestMessageOptions.MethodName | Identifies the option that stores the declared Refit interface method name. | None. Static read-only property. | string "Refit.MethodName". |
HttpRequestMessageOptions.RelativePathTemplate | Identifies the option that stores the unfilled route template for logging, metrics, and tracing. | None. Static read-only property. | string "Refit.RelativePathTemplate". |
HttpRequestMessageOptions.RequestContent | Identifies the option that stores a captured request body string when CaptureRequestContent is enabled. | None. Static read-only property. | string "Refit.RequestContent". |
HttpRequestMessageOptions.MethodArguments | Identifies 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.
BodySerializationMethod | Behavior |
|---|---|
Default = 0 | Passes HttpContent and streams through. Sends a string as plain text. Uses the configured serializer for other values. |
Serialized = 3 | Uses the configured serializer, including for strings. A JSON string includes quotes. |
UrlEncoded = 2 | Sends form key/value pairs. A dictionary or a generated property map supplies the fields. |
JsonLines = 4 | Sends an enumerable as one serialized value per line. Register the element types with the JSON context. |
Json = 1 | An obsolete name retained for compatibility. Use Serialized in new code. |
Buffering and serialization modes¶
Full description and examples.
RequestBodySerializationMode | Behavior |
|---|---|
Default = 0 | Uses the serializer's usual content method. System.Text.Json uses its async metadata path. |
Buffered = 1 | Uses ISynchronousContentSerializer to write a complete byte buffer. |
Streamed = 2 | Uses that interface to write into the outgoing stream without storing the whole body. |
Compression and ownership¶
Full description and examples.
RequestCompression | Result |
|---|---|
Default = 0 | The attribute takes coding and level from settings. Settings set to Default do not compress. |
None = 1 | No coding; an attribute can opt out of a settings-level coding. |
GZip = 2 | Content-Encoding: gzip. |
Brotli = 3 | Content-Encoding: br on .NET 8 and later. |
Zstandard = 4 | Content-Encoding: zstd on .NET 11 and later. |
API reference¶
Full description and examples.
| API | Description | Parameters or value | Returns and behavior |
|---|---|---|---|
BodyAttribute | Marks 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. |
BodySerializationMethod | Selects how Refit turns a body value into HTTP content. | Enum values below. | Use with BodyAttribute to choose text, serialized, form, or JSON Lines content. |
RequestBodySerializationMode | Selects how Refit writes serialized JSON request content. | Enum values below. | Configure through RefitSettings.RequestBodySerialization. |
RequestCompression | Selects the content coding applied to a request body. | Enum values below. | Configure a default in RefitSettings or override it on BodyAttribute. |
RequestCompressionOptions | Holds optional compressor-specific settings that replace the resolved compression level for each coding. | Available on .NET 9 and later. | Assign it to RefitSettings.RequestCompressionOptions. |
TimeoutAttribute | Applies a per-call timeout to a Refit interface method. | Applies to a method. | A positive timeout cancels the request when it elapses. |
BodySerializationMethod.Default = 0 | Uses Refit's standard body rules. | 0 | Passes HttpContent and streams through, sends strings as plain text, and uses the configured serializer for other values. |
BodySerializationMethod.Json = 1 | Retains the former name for serialized content. | 1; obsolete. | Uses the configured serializer, including for strings. Use Serialized in new code. |
BodySerializationMethod.UrlEncoded = 2 | Writes form URL-encoded content. | 2 | A dictionary or object's fields supply form keys and values. |
BodySerializationMethod.Serialized = 3 | Serializes every body value with the configured content serializer. | 3 | Strings use the serializer too, so a JSON string includes its quotes. |
BodySerializationMethod.JsonLines = 4 | Writes newline-delimited JSON. | 4 | Serializes each enumerable item with the configured serializer and writes one item per line. |
RequestBodySerializationMode.Default = 0 | Uses the serializer's asynchronous JSON-content path. | 0 | System.Text.Json uses its metadata-based path. |
RequestBodySerializationMode.Buffered = 1 | Serializes JSON into a complete byte buffer before sending. | 1; requires ISynchronousContentSerializer. | Sends ByteArrayContent with Content-Length; suited to small and medium bodies. |
RequestBodySerializationMode.Streamed = 2 | Writes 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 = 0 | Inherits the coding from RefitSettings.RequestCompression. | 0 | Uses the settings coding and level. |
RequestCompression.None = 1 | Disables compression for this body. | 1 | Sends no content coding even when settings choose one. |
RequestCompression.GZip = 2 | Compresses the body with gzip. | 2; every Refit target. | Sends Content-Encoding: gzip. |
RequestCompression.Brotli = 3 | Compresses the body with Brotli. | 3; .NET 8 and later. | Sends Content-Encoding: br. |
RequestCompression.Zstandard = 4 | Compresses 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.Buffered | Gets the per-body buffering override. | Read-only bool?. | null uses RefitSettings.Buffered; true buffers content before sending and false skips it. |
BodyAttribute.SerializationMethod | Gets the selected body serialization method. | Read-only BodySerializationMethod; default Default. | Determines how ordinary body values become HTTP content. |
BodyAttribute.Compression | Gets 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.CompressionLevel | Gets 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.GZip | Gets or sets gzip-specific compressor settings. | Settable ZLibCompressionOptions?. | A non-null value replaces the resolved level for gzip; null uses that level. |
RequestCompressionOptions.Brotli | Gets or sets Brotli-specific compressor settings. | Settable BrotliCompressionOptions?. | A non-null value replaces the resolved level for Brotli; null uses that level. |
RequestCompressionOptions.Zstandard | Gets 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.Milliseconds | Gets 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.
| Input | Form field name | File name sent |
|---|---|---|
A part wrapper with Name set | Its Name, overriding [AliasAs] | Its nonempty FileName |
A wrapper with Name = null | [AliasAs], otherwise parameter name | Its nonempty FileName |
A wrapper with empty FileName | The same field-name rules | The parameter's aliased or declared name |
Raw Stream or byte[] | Aliased or declared parameter name | The same name |
Raw FileInfo | Aliased or declared parameter name | FileInfo.Name |
Raw HttpContent | Its existing content-disposition metadata | Its existing metadata |
| A string, formatted value or serialized model | Aliased or declared parameter name | None |
API reference¶
Full description and examples.
| API | Description | Parameters or value | Returns 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 Name | Creates the obsolete attribute; using it produces compiler warning CS0618. |
AttachmentNameAttribute.Name (obsolete) | Gets the legacy file-name override. | Read-only string | Returns 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 null | Stores the same byte array reference. Throws ArgumentNullException when value is null. |
ByteArrayPart.Value | Gets the bytes supplied to the constructor. | Read-only byte[] | Returns the original array. |
ByteArrayPart.CreateContent() (protected override) | Builds content for the byte-array part. | None | Returns 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 null | Stores the file information. Throws ArgumentNullException when value is null; it opens the file only when content is created. |
FileInfoPart.Value | Gets the source file information. | Read-only FileInfo | Returns the original FileInfo. |
FileInfoPart.CreateContent() (protected override) | Opens the source file and builds content for the part. | None | Returns StreamContent over a newly opened read stream. |
FormObjectAttribute() | Marks a complex multipart parameter for property flattening. | None | Causes 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.BoundaryText | Gets the boundary configured for the method. | Read-only string | Returns 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 type | Stores 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 name | Stores all three values. A null file name throws ArgumentNullException. |
MultipartItem.Name | Gets the explicit form field name for the item. | Read-only string? | Returns null when the constructor did not receive a name. |
MultipartItem.ContentType | Gets the optional media type for the item content. | Read-only string? | Returns the configured content type, or null. |
MultipartItem.FileName | Gets the file name sent in the multipart disposition. | Read-only string | Returns the required file name. |
MultipartItem.ToContent() | Creates this item's content and applies its nonempty ContentType. | None | Returns HttpContent. The caller disposes the returned content. |
MultipartItem.CreateContent() (protected abstract) | Defines how a derived item creates fresh underlying content. | None | Returns 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 null | Stores the stream without copying it. Throws ArgumentNullException when value is null; disposing its content leaves the caller's stream open. |
StreamPart.Value | Gets the caller-owned stream. | Read-only Stream | Returns the original stream. |
StreamPart.CreateContent() (protected override) | Wraps the stream without taking ownership of it. | None | Returns HttpContent that reads from Value. |
AttachmentNameAttribute (obsolete) | Legacy attribute for naming an attachment. | None | Attribute type; prefer the part wrapper types. |
ByteArrayPart | Represents byte-array content with multipart metadata. | None | Multipart item type derived from MultipartItem. |
FileInfoPart | Represents file content with multipart metadata. | None | Multipart item type derived from MultipartItem. |
FormObjectAttribute | Marks a complex parameter for multipart property flattening. | None | Parameter attribute type. |
MultipartAttribute | Marks a method whose body contains named multipart parts. | None | Method attribute type. |
MultipartItem | Base class for parts that carry a file name and optional content metadata. | None | Abstract type for custom multipart items. |
StreamPart | Represents caller-owned stream content with multipart metadata. | None | Multipart item type derived from MultipartItem. |
Results¶
Return types¶
Full description and examples.
Choose a shape¶
Full description and examples.
| Return type | What happens |
|---|---|
Task | Sends 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. |
PagedEnumerable<TPage, TItem> | Sends one request per page, lazily, and yields the items of every page. Needs the source generator and a [Paged] attribute. See pagination. |
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.
| Format | Content type | Body shape |
|---|---|---|
JsonArray | application/json, or another type not listed below | A JSON array such as [{"id":1,"name":"Ada"}]. |
JsonLines | application/jsonl, application/x-ndjson, or application/x-jsonlines | Each line holds a separate JSON value. |
ServerSentEvents | text/event-stream | Each 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.
| Property | Meaning |
|---|---|
IsReceived | A response message exists. False means no response arrived. |
IsSuccessStatusCode | A response exists and its status is 200–299. |
IsSuccessful | The status succeeds and Error is null. |
HasContent | Content is non-null. For a value type, its default value is also non-null. |
IsSuccessfulWithContent | Both IsSuccessful and HasContent are true. |
Content | The deserialized reply value, or default when unavailable. |
Error | A captured ApiExceptionBase, or null. An unsuccessful manually constructed wrapper may have no error. |
Settings | The settings supplied to the concrete wrapper. It keeps the same instance. |
RequestMessage | The request associated with this reply. The interface permits null; the concrete wrapper returns its constructor argument. |
StatusCode, ReasonPhrase, Version | The response status, reason text and HTTP version. Null when no response exists. |
Headers | The response headers. Null when no response exists. |
ContentHeaders | The body headers, such as its media type. Null when unavailable. |
Response API reference¶
Full description and examples.
| Member | Description | Parameters | Returns or value |
|---|---|---|---|
ApiRequestException | Represents 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. |
IApiResponse | Defines 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. |
ApiResponseExtensions | Provides 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>.Content | Stores 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>.ContentHeaders | Exposes headers belonging to the received response body. | None. | HttpContentHeaders?: content headers, or null when no response content exists. |
ApiResponse<T>.Error | Stores the captured transport, HTTP-status, or deserialization error. | None. | ApiExceptionBase?: the captured transport, HTTP, or deserialization error. |
ApiResponse<T>.HasContent | Reports whether the deserialized Content is non-null. | None. | bool; Content is non-null. |
ApiResponse<T>.IsSuccessfulWithContent | Reports 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>.Headers | Exposes headers from the received HTTP response. | None. | HttpResponseHeaders?: the received response headers, or null when no response arrived. |
ApiResponse<T>.IsReceived | Reports whether an HTTP response message was received. | None. | bool: true when an HTTP response arrived. |
ApiResponse<T>.IsSuccessStatusCode | Reports whether the received status code is in the 2xx range. | None. | bool: true when a received response has a 2xx status. |
ApiResponse<T>.IsSuccessful | Reports 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>.ReasonPhrase | Exposes the reason phrase returned with the HTTP status. | None. | string?: the server reason phrase, or null when none is available. |
ApiResponse<T>.RequestMessage | Exposes the request associated with the response wrapper. | None. | HttpRequestMessage: the request associated with this wrapper. |
ApiResponse<T>.Settings | Exposes the RefitSettings used to process the response. | None. | RefitSettings: the settings instance supplied to the constructor. |
ApiResponse<T>.StatusCode | Exposes the received HTTP status code, or null when no response arrived. | None. | HttpStatusCode?: the received status, or null when no response arrived. |
ApiResponse<T>.Version | Exposes 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.Headers | Exposes headers from the received HTTP response. | None. | HttpResponseHeaders?: the received response headers, or null when no response arrived. |
IApiResponse.ContentHeaders | Exposes headers belonging to the received response body. | None. | HttpContentHeaders?: headers for the received response body, or null when they are unavailable. |
IApiResponse.IsReceived | Reports whether an HTTP response message was received. | None. | bool: true when an HTTP response arrived. |
IApiResponse.IsSuccessStatusCode | Reports whether the received status code is in the 2xx range. | None. | bool: true when a received response has a 2xx status. |
IApiResponse.IsSuccessful | Reports 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.StatusCode | Exposes the received HTTP status code, or null when no response arrived. | None. | HttpStatusCode?: the received status, or null when no response arrived. |
IApiResponse.ReasonPhrase | Exposes the reason phrase returned with the HTTP status. | None. | string?: the server reason phrase, or null when none is available. |
IApiResponse.RequestMessage | Exposes the request associated with the response wrapper. | None. | HttpRequestMessage?: the request that led to the response, or null when unavailable. |
IApiResponse.Version | Exposes the HTTP version used by the received response. | None. | Version?: the received HTTP version, or null when no response arrived. |
IApiResponse.Error | Stores 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>.Content | Stores 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>.HasContent | Reports whether the deserialized Content is non-null. | None. | bool: true when Content is non-null. |
IApiResponse<T>.IsSuccessfulWithContent | Reports 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.
| Property | Meaning |
|---|---|
HttpMethod | The method supplied for the failed call. |
RequestMessage | The request, including its headers and local options. |
Uri | RequestMessage.RequestUri, which can be null. |
RefitSettings | The settings retained for the call and later error-body reading. |
RequestContent | Captured request-body text when enabled; you can replace it to remove private data. |
HasRequestContent | The captured text is neither null nor empty. Whitespace counts as present. |
Standard validation replies¶
Full description and examples.
ProblemDetails property | Meaning |
|---|---|
Type | A URI identifying the kind of problem; defaults to about:blank. |
Title | A short label for that kind of problem. |
Status | The status in the JSON document. It does not replace the actual HTTP status. |
Detail | Text about this occurrence. |
Instance | A URI identifying this occurrence. |
Errors | A mutable dictionary from field name to an array of validation messages. Empty by default. |
Extensions | A mutable dictionary for other JSON properties. Empty by default. |
Error API reference¶
Full description and examples.
| Member | Description | Parameters | Returns or value |
|---|---|---|---|
ApiExceptionBase | Abstract 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.HttpMethod | Identifies the HTTP method that Refit used for the failed request. | None. | HttpMethod: the method used by the failed call. |
ApiExceptionBase.Uri | Exposes the request URI when the retained request has one. | None. | Uri?: RequestMessage.RequestUri. |
ApiExceptionBase.RequestMessage | Gives access to the live request, including headers and request options. | None. | HttpRequestMessage: the request, including its headers and local options. |
ApiExceptionBase.RequestContent | Holds 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.HasRequestContent | Lets 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.RefitSettings | Gets the settings that governed the failed call. | None. | RefitSettings: settings retained for the call and later error-body reading. |
ApiException | Represents 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.StatusCode | Identifies the HTTP status sent by the server. | None. | HttpStatusCode: the received HTTP response status. |
ApiException.ReasonPhrase | Preserves the optional reason phrase sent with the HTTP status. | None. | string?: the server reason phrase, if supplied. |
ApiException.Headers | Provides the response headers retained from the failed response. | None. | HttpResponseHeaders: the received response headers. |
ApiException.ContentHeaders | Provides headers belonging to the buffered response body. | None; protected setter. | HttpContentHeaders?: headers for the captured response body. |
ApiException.Content | Holds 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.HasContent | Tests whether Content contains non-whitespace response text. | None. | bool: true when Content is not null, empty, or whitespace. |
DefaultApiExceptionFactory | Supplies 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. |
ProblemDetails | Models 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.Errors | Maps each invalid field name to its validation messages. | None; init only. | Dictionary<string, string[]>; default empty. |
ProblemDetails.Extensions | Stores JSON properties that are not standard problem-details fields. | None; init only. | IDictionary<string, object>; default empty. |
ProblemDetails.Type | Identifies the kind of problem, usually with a URI. | string? value. | A URI that identifies the problem kind; default about:blank. |
ProblemDetails.Title | Gives a short human-readable label for the problem kind. | string? value. | A short label for the problem kind; default null. |
ProblemDetails.Status | Carries 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.Detail | Explains this particular problem occurrence. | string? value. | Text about this problem occurrence; default null. |
ProblemDetails.Instance | Identifies this particular problem occurrence, usually with a URI. | string? value. | A URI that identifies this problem occurrence; default null. |
ValidationApiException | Represents 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.Content | Exposes 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.
| Member | Description | Parameters | Returns 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.ReturnTypeAdapters | Exposes 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. |
Pagination¶
Full description and examples.
Types: Refit.PagedEnumerable<TPage, TItem>, Refit.PagedEnumerable, Refit.PagedAttribute, Refit.PageTokenAttribute, Refit.PageContinuation, Refit.PageContinuation<TToken> and Refit.NextLinkOriginPolicy.
Declare a paged method¶
Full description and examples.
| Member | Description | Parameters | Returns or value |
|---|---|---|---|
PagedAttribute | Marks a method that returns PagedEnumerable<TPage, TItem>, so the source generator emits its paging loop. | None. | Method attribute type. |
PagedAttribute.Items | Names the member of the page that holds the items. | Nullable string, dotted for nested members. When omitted, the page must have exactly one sequence of the item type. | The member the generator reads; a misspelled name is a build error. |
PagedAttribute.Next | Names the member of the page that holds the next token, offset or link. | Nullable string, dotted for nested members. The member must be nullable. | null or an empty string ends the sequence. |
PagedAttribute.NextHeader | Names the response header that holds the next token or link. | Nullable string. The page type must be ApiResponse<T> or IApiResponse. | Link is read for its rel="next" entry; any other header is read as the whole value. |
PagedAttribute.Total | Names the member of the page that holds the total item count. | Nullable string. The token parameter must be an int. | The sequence ends when the offset reaches the total or a page is empty. |
PagedAttribute.Origins | Lists the origins a next link may point at. | Nullable string[] of absolute http or https addresses. | A link to any other origin is refused and never requested. |
PagedAttribute.SameOrigin | Restricts next links to the origin of the client's BaseAddress. | bool, default false. | Exactly one of Origins, SameOrigin and AnyOrigin is required for a method that follows links. |
PagedAttribute.AnyOrigin | Lets next links point at any http or https origin. | bool, default false. | The client's credentials go to whatever origin the server names. |
PageTokenAttribute | Marks the parameter that carries the continuation. | None. | Parameter attribute type. The argument is the token of the first page. |
Read the sequence¶
Full description and examples.
| Member | Description | Parameters | Returns or value |
|---|---|---|---|
PagedEnumerable<TPage, TItem> | A lazy sequence of items that also exposes the pages. Every enumeration starts again from the first page. | TPage: the page type, your DTO or an ApiResponse<T> of it. TItem: the item type. | Implements IAsyncEnumerable<TItem>. |
AsPages() | Exposes the pages as the service returned them. | None. | IAsyncEnumerable<TPage>; each page is disposed when you move past it. |
WithMaxPages(int pages) | Bounds the pages fetched. | int pages: positive limit. | A new PagedEnumerable<TPage, TItem>. Throws ArgumentOutOfRangeException unless pages is positive. |
WithPrefetch() | Requests the next page while you read the current one. | None. | A new PagedEnumerable<TPage, TItem> that reads at most one page ahead. |
ToObservable() | Exposes the items as a cold observable. | None. | IObservable<TItem>; each subscription starts from the first page, and disposing it cancels the request in flight. |
ToPageObservable() | Exposes the pages as a cold observable. | None. | IObservable<TPage>; a page is disposed after OnNext returns. |
Write the loop yourself¶
Full description and examples.
| Member | Description | Parameters | Returns or value |
|---|---|---|---|
PagedEnumerable.Create<TPage, TItem, TToken>(fetch, items, next) | Wraps a method that fetches one page for a token. The first page is requested with default(TToken). | fetch: Func<TToken, CancellationToken, Task<TPage>>. items: Func<TPage, IEnumerable<TItem>?>. next: Func<TPage, TToken, PageContinuation<TToken>>. | A PagedEnumerable<TPage, TItem> that requests nothing until it is enumerated. Throws ArgumentNullException for a null delegate. |
PagedEnumerable.Create<TPage, TItem, TToken>(first, fetch, items, next) | The same, starting from a token you supply. | first: the token of the first page; the delegates are as above. | A PagedEnumerable<TPage, TItem>. |
PagedEnumerable.FromCursor<TPage, TItem>(fetch, items, nextCursor) | Wraps an API whose next page is named by a string cursor. | fetch: Func<string?, CancellationToken, Task<TPage>>. nextCursor: Func<TPage, string?>. | A sequence that ends on a null or empty cursor. |
PagedEnumerable.FromOffset<TPage, TItem>(fetch, items, nextOffset) | Wraps an API addressed by the index of the first item, starting at zero. | fetch: Func<int, CancellationToken, Task<TPage>>. nextOffset: Func<TPage, int, int?>. | A sequence that ends when nextOffset returns null. |
PagedEnumerable.FromLinks<TPage, TItem>(originPolicy, fetch, items, nextLink) | Wraps an API whose reply names the next page with a link. | originPolicy: NextLinkOriginPolicy. fetch: Func<Uri?, CancellationToken, Task<TPage>>, called with null for the first page. nextLink: Func<TPage, Uri?>. | A sequence that follows only the links the policy allows. A refused link throws InvalidOperationException without being requested. |
PageContinuation.To<TToken>(TToken next) | Creates a continuation to the next page. | next: the token for the next fetch. | A continuation, or the end of the sequence when next is null or an empty string. |
PageContinuation<TToken> | Says whether another page follows and which token requests it. | None. | HasNext, Token and End. |
NextLinkOriginPolicy.Allow(params Uri[] origins) | Creates a policy that follows only links whose scheme, host and port match a listed origin. | Uri[] origins: at least one absolute http or https address. | A policy. Throws ArgumentException for an empty list or a relative address. |
NextLinkOriginPolicy.Unrestricted | A policy that follows a link to any http or https origin. | None. | The shared unrestricted policy. |
NextLinkOriginPolicy.IsAllowed(Uri link) | Tests whether a link may be followed. | Uri link: non-null. | true for an absolute http or https link without user information on an allowed origin. |
IApiResponse.GetLink(string relation) | Reads the target of the first Link response header entry with a relation. | string relation: such as next, compared without regard to case. | Uri?: the target, which may be relative, or null when there is none. |
Serialization¶
JSON and generated metadata¶
Full description and examples.
Types: Refit.IHttpContentSerializer, Refit.IJsonTypeInfoContentSerializer, Refit.ISynchronousContentDeserializer, Refit.ISynchronousContentSerializer, Refit.SystemTextJsonContentSerializer.
Serializer capabilities¶
Full description and examples.
| Interface | Description |
|---|---|
IHttpContentSerializer | Defines the required request-body writer, response-body reader and reflected property-name hook. |
ISynchronousContentSerializer | Adds synchronous buffered and streamed request-body writers. Refit uses them for Buffered and Streamed request-body modes. |
ISynchronousContentDeserializer | Adds a reader for an error body that Refit has already buffered as a string. |
IStreamingContentSerializer | Adds an incremental response reader for Refit interface methods that return IAsyncEnumerable<T>. |
IJsonTypeInfoContentSerializer | Adds writers and readers that take a JsonTypeInfo<T> for one call. Refit uses them for a method that has a JsonTypeInfo<T> parameter. Only SystemTextJsonContentSerializer implements it. Available on .NET 8 and later. |
| API | Description | Parameters | Returns and behavior |
|---|---|---|---|
SystemTextJsonContentSerializer() | Creates a serializer with Refit's default JSON configuration. | None | Creates 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. |
ForContext(JsonSerializerContext context) | Creates a serializer that runs on a context's own options, with reflection-based JSON off. | context: JsonSerializerContext, the generated context. | Returns a SystemTextJsonContentSerializer whose options are the context's options. A type the context does not list throws NotSupportedException. Available on .NET 8 and later. |
ForContext(JsonSerializerContext context, bool allowReflectionFallback) | Creates a serializer that runs on a context's own options, optionally with a reflection fallback. | context: the generated context; allowReflectionFallback: true lets a type the context does not list use reflection-based JSON. Not trim or Native AOT safe. | Returns a serializer. With false it uses the context's options unchanged. With true it adds a reflection resolver after the context. |
WithContext(JsonSerializerContext context) | Creates a serializer that keeps this serializer's options and adds a context, with reflection-based JSON off. | context: the generated context that supplies metadata for the types it lists. | Returns a serializer built on a copy of this serializer's options, or this serializer when the context is registered. The naming policy, converters and other options come from this serializer. Resolvers it holds stay first and in order. Contract modifiers of a reflection resolver move onto the context. |
WithContext(JsonSerializerContext context, bool allowReflectionFallback) | Creates a serializer that keeps this serializer's options and adds a context, optionally with a reflection fallback. | context; allowReflectionFallback: true lets a type no resolver lists use reflection-based JSON. Not trim or Native AOT safe. | Returns a serializer built like WithContext(context). With true it keeps or adds a reflection resolver after the context. |
SerializerOptions | Gets the configuration used by this serializer. | None | Returns the same JsonSerializerOptions instance passed to the constructor or created by the default constructor. |
GetDefaultJsonSerializerOptions() | Creates Refit's general-purpose JSON configuration. | None | Returns 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. | None | Returns 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. |
ToHttpContent<T>(T item, JsonTypeInfo<T> typeInfo) | Serializes a request value with the metadata you pass. | item: T, the request value; typeInfo: JsonTypeInfo<T>, the metadata for T, such as a property of a context. | Returns JSON HttpContent. |
ToHttpContentSynchronous<T>(T item, JsonTypeInfo<T> typeInfo) | Serializes a request value immediately into a buffered body with the metadata you pass. | item: T; typeInfo: the metadata for T. | Returns UTF-8 JSON HttpContent with a ByteArrayContent body. |
ToStreamingHttpContent<T>(T item, JsonTypeInfo<T> typeInfo) | Creates a body that serializes a value with the metadata you pass when the request sends it. | item: T; typeInfo: the metadata for T. | Returns HttpContent that writes UTF-8 JSON to the request stream. |
FromHttpContentAsync<T>(HttpContent content, JsonTypeInfo<T> typeInfo, CancellationToken cancellationToken = default) | Reads a JSON HTTP body with the metadata you pass. | content: the response body; typeInfo: the metadata for T; cancellationToken: cancels the read. Default: default. | Returns Task<T?> for the value, or null for JSON null. |
DeserializeFromString<T>(string content, JsonTypeInfo<T> typeInfo) | Reads buffered JSON text with the metadata you pass. | content: the JSON text; typeInfo: the metadata for T. | Returns T?, the deserialized value. |
DeserializeStreamAsync<T>(Stream stream, StreamingContentFormat format, JsonTypeInfo<T> typeInfo, CancellationToken cancellationToken = default) | Reads one value at a time from a framed response stream with the metadata you pass. | stream: the response body; format: the framing; typeInfo: the metadata for one element, whose options drive the read; cancellationToken: cancels enumeration. Default: default. | Returns IAsyncEnumerable<T?> that yields values as they arrive. |
Defaults and fast-path writers¶
Full description and examples.
| Condition | What to do |
|---|---|
| Generated writer exists | Use Default or Serialization generation mode. Keep metadata too when you read replies. |
| No custom converters | Avoid entries in JsonSerializerOptions.Converters and JsonConverter attributes on the model or its members. |
| Compatible options | Keep naming, ignored-member and null-handling options aligned with the generated context. |
| Supported features | Avoid custom encoders, dictionary key policies and reference handling for this path. |
| Supported number writing | Avoid 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.
| API | Description | Parameters | Returns and behavior |
|---|---|---|---|
NewtonsoftJsonContentSerializer | Implements 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 member | Description | Default 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. |
XmlDefaultNamespace | string?; 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. |
XmlReaderWriterSettings | XmlReaderWriterSettings; the paired reader and writer configuration. | Defaults to a new instance. Accessing its reader or writer applies asynchronous operation and safe DTD settings. |
XmlNamespaces | XmlSerializerNamespaces; namespace prefixes and URIs supplied to XmlSerializer.Serialize. | Defaults to one empty-prefix/empty-namespace mapping. |
XmlAttributeOverrides | XmlAttributeOverrides; alternate XML mappings for model types. | Defaults to an empty collection. Overrides are read when a type's cached XmlSerializer is created. |
XmlReaderWriterSettings member | Description | Behavior |
|---|---|---|
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. |
ReaderSettings | XmlReaderSettings; 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. |
WriterSettings | XmlWriterSettings; gets or replaces the writer settings. | Assignment rejects null. Getting the value sets Async = true. |
AllowDtdProcessing | bool; 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 member | Description | Parameters | Returns and behavior |
|---|---|---|---|
XmlContentSerializer() | Creates an XML content serializer with default settings. | None | Uses a new XmlContentSerializerSettings. |
XmlContentSerializer(XmlContentSerializerSettings settings) | Creates an XML content serializer with caller-supplied settings. | settings: non-null XmlContentSerializerSettings | Stores the settings; null throws ArgumentNullException. |
ToHttpContent<T>(T item) | Serializes a value for an XML HTTP request. | item: value to serialize | Returns 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 default | Returns 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 XML | Returns 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 inspect | Returns 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.
| Format | Body framing |
|---|---|
JsonArray = 0 | One top-level JSON array; each array element is yielded. |
JsonLines = 1 | JSON values separated by whitespace on .NET 9 and later. |
ServerSentEvents = 2 | An SSE stream; each event's data payload is deserialized as JSON. |
Infer values stored as object¶
Full description and examples.
| JSON token | Result |
|---|---|
true or false | bool |
| Number representable as Int64 | long |
| Other number | double |
| String parseable as DateTime | DateTime |
| Other string | string |
| Object, array or a directly read null token | A detached JsonElement |
API reference¶
Full description and examples.
| API | Description | Parameters | Returns and behavior |
|---|---|---|---|
StreamingContentFormat | Names the framing used by a streaming content serializer. | None | An enum with JsonArray, JsonLines, and ServerSentEvents values. |
StreamingContentFormat.JsonArray = 0 | Selects one top-level JSON array. | None | Each array element is yielded as one T value. |
StreamingContentFormat.JsonLines = 1 | Selects newline-delimited JSON values. | None | Each JSON value is yielded as one T value. |
StreamingContentFormat.ServerSentEvents = 2 | Selects server-sent events. | None | Each event's data field is deserialized and yielded as one T value. |
IStreamingContentSerializer | Defines the optional capability to deserialize response bodies incrementally. | None | Implement 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. | None | A public class implementing IHttpContentSerializer; its compiler error prevents direct use. |
JsonLinesContent | Represents an HTTP body that writes one serialized value per JSON Lines record. | None | A sealed HttpContent implementation. |
ObjectToInferredTypesConverter | Infers CLR values when System.Text.Json deserializes a value declared as object. | None | A 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 value | Creates HttpContent. Throws ArgumentNullException for either argument. |
JsonLinesContent.JsonLinesMediaType | Identifies the media type emitted by JSON Lines content. | None | Returns 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 TransportContext | Returns 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 -1 | Returns 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 enumeration | Returns IAsyncEnumerable<T?>. Malformed data or missing metadata fails during enumeration. |
JsonContentSerializer() (obsolete) | Represents the obsolete JSON serializer compatibility type. | None | Constructs 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 serialize | Returns 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 cancellation | Returns 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 inspect | Returns string in the signature, but always throws NotSupportedException. |
ObjectToInferredTypesConverter() | Creates the converter used to infer CLR values when deserializing object. | None | Creates 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, JsonSerializerOptions | Returns 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, JsonSerializerOptions | Returns 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 reads | Returns 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.
| API | Description | Parameters | Returns and behavior |
|---|---|---|---|
StubHttp | Declarative HttpMessageHandler for Refit tests; stores route matchers and their replies, records requests, and supports one-shot, reusable and fallback routes. | None | Handler type implementing IEnumerable<RouteMatcher>. |
StubHttp() | Starts a handler with no expected routes. | None | Creates 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 request | Creates an empty route table with the supplied behavior. |
StubHttp.Requests | Exposes requests received by the handler in arrival order. | Get-only IReadOnlyList<HttpRequestMessage> | Returns a live read-only view, including unmatched and failed requests. |
StubHttp.Behavior | Enables, replaces or disables simulated network conditions. | Nullable NetworkBehavior, get/set; default null | Gets 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: StubResponse | Returns void; rejects null arguments and tracks one-shot expectations. |
StubHttp.ToSettings() | Creates settings that route a Refit client through this handler. | None | Returns new RefitSettings whose handler factory returns this handler. |
StubHttp.ToSettings(RefitSettings baseSettings) | Reuses supplied settings and points them at this handler. | baseSettings: RefitSettings to update | Returns 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 address | Returns 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 handler | Returns 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 address | Returns 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 handler | Returns 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: CancellationToken | Returns 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.
| Property | Required request behavior |
|---|---|
Method | Same HTTP method. Null accepts any method. |
Query | Contains each decoded key/value pair. Extra pairs are allowed. |
ExactQuery | Same decoded pairs and count as the supplied encoded query, ignoring order. Omit the leading ?. |
ExactQueryParams | Same decoded pairs and count as the supplied array, ignoring order. |
Headers | Contains each name/value pair in request or content headers. Names use HTTP header lookup. Values compare exactly. Multiple values join with ", ". |
Body | Exact body text. Missing content counts as an empty string. |
FormData | Contains each decoded form pair. Extra pairs are allowed. The media type is not checked. |
Where | The synchronous predicate returns true. |
WhereAsync | The asynchronous predicate returns true. It runs after Where passes. |
API reference¶
Full description and examples.
| API | Description | Parameters or value | Returns and behavior |
|---|---|---|---|
Route | Provides 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. |
RouteMatcher | Describes 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.Method | Restricts 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.Template | Supplies 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.Query | Requires 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.ExactQuery | Requires 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.ExactQueryParams | Requires 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.Headers | Requires selected request or content headers. | Init-only nullable array of (string Name, string Value) pairs. | Every supplied header name and value must occur. |
RouteMatcher.Body | Requires 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.FormData | Requires 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.Where | Adds 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.WhereAsync | Adds 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.Reusable | Makes a route available for repeated background behavior. | Init-only bool; default false. | true allows repeated matches and excludes the route from VerifyAllCalled. |
RouteMatcher.Fallback | Makes 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.
| Method | Body 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.
| API | Description | Parameters | Returns and behavior |
|---|---|---|---|
Reply.With<T>(T body) | Creates a typed successful reply using the handler's serializer. | body: generic type T | Returns 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: HttpStatusCode | Returns StubResponse with serialized content and the supplied status. |
Reply.Json(string body) | Creates a successful reply from raw JSON text. | body: string JSON text | Returns 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: HttpStatusCode | Returns JSON StubResponse with the supplied status. |
Reply.Text(string body) | Creates a plain-text successful reply. | body: string text | Returns 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 type | Returns 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 status | Returns a StubResponse. |
Reply.Content(HttpContent body) | Reuses an explicit HTTP content instance as a reply body. | body: HttpContent exact content instance | Returns 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 function | Returns 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> result | Returns StubResponse whose async responder supplies the complete HttpResponseMessage. |
StubResponse() | Creates an empty response description that you can configure with init properties. | None | Creates a StubResponse with HttpStatusCode.OK. |
StubResponse.Status | Chooses the status for a property-based reply. | HttpStatusCode, init-only; default HttpStatusCode.OK | Sets the response status unless a responder supplies the complete response. |
StubResponse.Json | Supplies the raw JSON alternative to a typed or explicit body. | Nullable string, init-only; default null | Supplies raw JSON text. |
StubResponse.Text | Supplies a raw text alternative to a typed or explicit body. | Nullable string, init-only; default null | Supplies raw text. |
StubResponse.ContentType | Chooses the media type used when Text supplies the body. | Nullable string, init-only; default null | Sets media type for Text; it does not alter JSON or explicit content. |
StubResponse.Content | Supplies an exact content object in preference to text and JSON. | Nullable HttpContent, init-only; default null | Supplies exact content and takes precedence over JSON/text bodies. |
StubResponse.Responder | Supplies the whole response through a synchronous callback. | Nullable Func<HttpRequestMessage, HttpResponseMessage>, init-only; default null | Supplies a complete HttpResponseMessage synchronously. |
StubResponse.ResponderAsync | Supplies the whole response through an asynchronous callback. | Nullable Func<HttpRequestMessage, Task<HttpResponseMessage>>, with Task<TResult> result; init-only; default null | Supplies 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.
| Overload | Description | Parameters | Returns |
|---|---|---|---|
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. |
| Property | Type | Value |
|---|---|---|
Requests | IReadOnlyList<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.
| Overload | Description | Parameters | Returns |
|---|---|---|---|
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. |
| Property | Type | Default and behavior |
|---|---|---|
Delay | TimeSpan | Two seconds. Base delay for simulation. |
Variance | double | 0.4. Fraction above and below the delay. Zero fixes the delay. |
FailurePercent | double | 0.03. Connection-failure probability. |
ErrorPercent | double | 0. HTTP-error probability when no connection failure occurs. |
ErrorStatusCode | HttpStatusCode | InternalServerError (500). Injected response status. |
FailureFactory | Func<Exception> | Creates an HttpRequestException with message Refit.Testing simulated network failure. |
StubHttp.Behavior | NetworkBehavior, nullable | Constructor-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.
| Property | Type | Default and what the test supplies |
|---|---|---|
Content | T? | default(T). Typed body for the scenario. |
HasContent | bool | false. Whether the test promises non-null content. |
IsSuccessfulWithContent | bool | false. Whether success and non-null content are both promised. |
IsSuccessStatusCode | bool | false. Whether the supplied status is 200–299. |
IsSuccessful | bool | false. Whether status succeeds and no error occurred. |
IsReceived | bool | false. Whether a reply arrived. |
StatusCode | HttpStatusCode, nullable | null. Reply status for the scenario. |
ReasonPhrase | string, nullable | null. Reply reason phrase. |
Version | Version, nullable | null. HTTP version. |
Headers | HttpResponseHeaders, nullable | null. Reply header collection. |
ContentHeaders | HttpContentHeaders, nullable | null. Body header collection. |
RequestMessage | HttpRequestMessage, nullable | null. Associated request. |
Error | ApiExceptionBase, nullable | null. Exception for a simulated failure. |
Select an error kind¶
Full description and examples.
| Overload | Description | Parameters | Returns |
|---|---|---|---|
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.
| Overload | Description | Parameters | Returns |
|---|---|---|---|
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.
| Overload | Description | Parameters | Returns |
|---|---|---|---|
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. |
SetRequestJsonTypeInfo<T>(HttpRequestMessage request, JsonTypeInfo<T>? typeInfo) | Stores the metadata that describes the response body, so the reply is read with it. Generated code calls it for a method that has a JsonTypeInfo<T> parameter. | HttpRequestMessage request; JsonTypeInfo<T> typeInfo: metadata for the reply body, or null to store nothing. .NET 8 and later. | void; stores the metadata as a request option. |
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.
| Overload | Description | Parameters | Returns |
|---|---|---|---|
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. |
CreateBodyContent<TBody>(RefitSettings settings, TBody body, JsonTypeInfo<TBody>? typeInfo, BodySerializationMethod serializationMethod, bool streamBody) | Serializes a request body with the metadata a method parameter supplies. It follows the same body rules as the overload above. | RefitSettings settings; body: value to send; JsonTypeInfo<TBody> typeInfo: metadata for TBody, or null to use the serializer's own lookup; BodySerializationMethod serializationMethod; bool streamBody. | HttpContent: as above, with the body written through IJsonTypeInfoContentSerializer when typeInfo is set. Throws InvalidOperationException when the serializer does not implement it. .NET 8 and later. |
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.
| Parameter | Type | Value |
|---|---|---|
isApiResponse | bool | true when T is a supported response wrapper. |
shouldDisposeResponse | bool | true for a fully consumed result. Use false when returning a live response owner. |
bufferBody | bool | Whether to buffer request content before sending. |
| Overload | Description | Parameters | Returns |
|---|---|---|---|
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.
| Overload | Description | Parameters | Returns |
|---|---|---|---|
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. |
| Property | Type | Value |
|---|---|---|
Getter | Func<TBody, object?> | Reads the field value from a body instance. |
ClrName | string | Declared property name. |
ExplicitName | string, nullable | Alias or serializer name; null uses the key formatter. |
PrefixSegment | string, nullable | Prefix including delimiter; null adds none. |
Format | string, nullable | Value format; null uses default formatting. |
CollectionFormat | CollectionFormat, nullable | Explicit collection rule; null uses settings. |
SerializeNull | bool | true emits an empty field for null; false omits it. |
UrlResolutionMode value | Numeric value | Meaning |
|---|---|---|
RefitLegacy | 0 | Prefix the base-address path and require a leading slash. |
Rfc3986 | 1 | Use 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.
| Format | Result |
|---|---|
Multi | One pair per non-null element; an empty collection emits nothing. |
Csv or RefitParameterFormatter | One comma-joined value. |
Ssv | One value joined with spaces. |
Tsv | One value joined with tabs. |
Pipes | One value joined with vertical bars. |
Indexed | This low-level helper joins with commas. Generated query-object code performs indexed expansion separately. |
Query builder API reference¶
Full description and examples.
| Type | Purpose |
|---|---|
GeneratedQueryStringBuilder | A stack-only builder that appends an escaped query string to a relative request path without reflection. |
GeneratedParameterAttributeProvider | Supplies attributes from a dictionary when a generated parameter has more than one attribute type. |
GeneratedSingleTypeParameterAttributeProvider | Supplies one type's attributes without allocating a dictionary or flattening arrays. |
| Overload | Description | Parameters | Returns |
|---|---|---|---|
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.
| Overload | Description | Parameters | Returns |
|---|---|---|---|
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. |
| Field | Description | Type | Value |
|---|---|---|---|
GeneratedParameterAttributeProvider.Empty | Reuses one provider for parameters that declare no attributes. | GeneratedParameterAttributeProvider | Shared static readonly provider with no attributes. |
| Overload | Description | Parameters | Returns |
|---|---|---|---|
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.
| Overload | Description | Parameters | Returns |
|---|---|---|---|
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. |
| Property | Type | Value and access |
|---|---|---|
Name | string | Method name supplied to the constructor; get; init;. |
HostingType | Type | Declaring interface supplied to the constructor; get; init;. |
MethodInfo | MethodInfo | Reflected method supplied to the constructor; get; init;. |
RelativePath | string | Route template supplied to the constructor; get; init;. |
ReturnType | Type | Declared result type supplied to the constructor; get; init;. |
Parameter metadata reference¶
Full description and examples.
| Overload | Description | Parameters | Returns |
|---|---|---|---|
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. |
| Property | Type | Value and access |
|---|---|---|
RestMethodParameterInfo.Name | string, nullable | Name supplied to the named constructor, or null for the flag constructor; get; set;. |
RestMethodParameterInfo.ParameterInfo | ParameterInfo | Reflected parameter supplied to either constructor; get; set;. |
RestMethodParameterInfo.IsObjectPropertyParameter | bool | Whether the binding reads object properties; defaults to false in the named constructor; get; set;. |
RestMethodParameterInfo.ParameterProperties | List<RestMethodParameterProperty> | Starts empty. The list can be replaced during initialization and its contents can be changed later; get; init;. |
RestMethodParameterInfo.Type | ParameterType | Starts as Normal; get; set;. See the values below. |
RestMethodParameterProperty.Name | string | Binding name supplied to either constructor; get; set;. |
RestMethodParameterProperty.PropertyInfo | PropertyInfo | Final property to read; get; set;. Assigning it does not change PropertyChain. |
RestMethodParameterProperty.PropertyChain | IReadOnlyList<PropertyInfo> | Ordered navigation chain; get; set;. Assigning it does not change PropertyInfo. |
ParameterType value | Numeric value | Meaning |
|---|---|---|
Normal | 0 | Ordinary route value escaping. |
RoundTripping | 1 | Catch-all path handling that retains / separators. |
Client name overloads¶
Full description and examples.
| Overload | Description | Parameters | Returns |
|---|---|---|---|
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. |