Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
R

refit

> 编程语言
Open source

The automatic type-safe REST library for .NET Core, Xamarin and .NET. Heavily inspired by Square's Retrofit library, Refit turns your REST API into a live inter

9.6K stars0 likes3 views
WebsiteGitHub

About

The automatic type-safe REST library for .NET Core, Xamarin and .NET. Heavily inspired by Square's Retrofit library, Refit turns your REST API into a live inter

Refit: The automatic type-safe REST library for modern .NET

Refit Refit.HttpClientFactory Refit.Newtonsoft.Json Refit.Testing
NuGet

Refit is a library heavily inspired by Square's Retrofit library, and it turns your REST API into a live interface:

csharp
public interface IGitHubApi
{
    [Get("/users/{user}")]
    Task<User> GetUser(string user);
}

The RestService class generates an implementation of IGitHubApi that uses HttpClient to make its calls:

csharp
var gitHubApi = RestService.For<IGitHubApi>("https://api.github.com");
var octocat = await gitHubApi.GetUser("octocat");

.NET supports registering Refit clients via HttpClientFactory:

csharp
services
    .AddRefitClient<IGitHubApi>()
    .ConfigureHttpClient(c => c.BaseAddress = new Uri("https://api.github.com"));

To test the clients you build with Refit, the Refit.Testing package lets you stub responses and verify requests with a declarative route table — see Testing your Refit clients.

Table of Contents

  • Sponsors
  • Where does this work?
  • SDK Requirements
  • Breaking changes and release notes
  • Source generation
    • Generated-only client creation
    • Generated request building
  • API Attributes
  • Querystrings
    • Dynamic Querystring Parameters
    • Collections as Querystring parameters
    • Unescape Querystring parameters
    • Valueless query flags
    • Custom Querystring Parameter formatting
  • Body content
    • Buffering and the Content-Length header
    • JSON content
    • JSON Lines content
    • XML Content
    • Form posts
  • Setting request headers
    • Static headers
    • Dynamic headers
    • Bearer Authentication
    • Scoped (per-request) authorization tokens with dependency injection
    • Reducing header boilerplate with DelegatingHandlers (Authorization headers worked example)
    • Redefining headers
    • Removing headers
    • Validating header values
  • Passing state into DelegatingHandlers
    • Support for Polly and Polly.Context
    • Target Interface type
    • MethodInfo of the method on the Refit client interface that was invoked
  • Per-request timeouts
  • Multipart uploads
  • Retrieving the response
  • Using generic interfaces
  • Interface inheritance
    • Composing multiple APIs into one client
    • Headers inheritance
  • Default Interface Methods
  • Using HttpClientFactory
  • Providing a custom HttpClient
  • Handling exceptions
    • When returning Task<IApiResponse>, Task<IApiResponse<T>>, or Task<ApiResponse<T>>
    • When returning Task<T>
    • Inspecting the error body synchronously
    • Reading the request body that was sent
    • Providing a custom ExceptionFactory
    • Providing a custom TransportExceptionFactory
    • ApiException deconstruction with Serilog
  • Testing your Refit clients

Sponsors

Refit is sponsored by the following:

Where does this work?

Refit currently supports the following platforms and modern .NET targets:

  • WinUI
  • Desktop .NET Framework 4.6.2+
  • .NET 8 / 9 / 10 / 11
  • Blazor
  • Uno Platform

SDK Requirements

The source generator ships inside the Refit package as a Roslyn analyzer, so it is your build tools, not your target framework, that decide whether you get generated clients:

Requirement Minimum
Roslyn (C# compiler) 4.8
Visual Studio 2022 17.8
.NET SDK 8.0.100
NuGet references PackageReference

These are build-time requirements only. The compiled output still runs on every platform listed above, down to .NET Framework 4.6.2, and both SDK-style and legacy (non-SDK) .csproj projects are supported.

Older build tools do not silently produce an empty client — the build fails with REFIT001 naming the Roslyn version it found. packages.config cannot load analyzers at all, so a source generator will never run there; migrate to PackageReference to use it.

If you cannot move to these build tools, set DisableRefitSourceGenerator to true and add the Refit.Reflection package, which builds requests at runtime and needs no source generator.

Breaking changes and release notes

Breaking changes and the notable additions for each major version — including the V14 move of the reflection request builder into the opt-in Refit.Reflection package — are documented in Breaking changes and release notes.

Source generation

The Refit package ships Roslyn source generators. A PackageReference to Refit gets you generated clients at build time — no extra package.

The generated code targets C# 7.3. On C# 8 or newer, the generator also emits nullable directives and annotations.

You create generated clients with the normal APIs:

csharp
var api = RestService.For<IGitHubApi>("https://api.github.com");

or through Refit.HttpClientFactory:

csharp
services
    .AddRefitClient<IGitHubApi>()
    .ConfigureHttpClient(c => c.BaseAddress = new Uri("https://api.github.com"));

Generated clients use the same RefitSettings you pass to RestService.For<T> or AddRefitClient<T>, and honor settings such as:

  • ContentSerializer
  • UrlParameterFormatter
  • UrlParameterKeyFormatter
  • CollectionFormat
  • AuthorizationHeaderValueGetter
  • ExceptionFactory
  • DeserializationExceptionFactory
  • TransportExceptionFactory
  • HttpRequestMessageOptions
  • Version and VersionPolicy

Automatic client registration

On .NET 5 and newer the generator emits a module initializer that registers every generated client factory at assembly load. RestService.ForGenerated<T> and AddRefitGeneratedClient<T> then resolve the client with no runtime reflection. RestService.For<T> skips the reflection request builder for fully generated interfaces. That keeps trimmed and Native AOT apps reflection-free.

.NET Framework (net462–net481) gets no automatic registration. ModuleInitializerAttribute arrived in .NET 5 and isn't in the .NET Framework BCL, so Refit emits the initializer only for .NET 5+ targets. Raising a project's <LangVersion> to 9 doesn't change that — the missing type is the blocker, not the language version. (It does switch on modern generated syntax like nullable annotations.)

The generated inline code still runs. But RestService.For<T> finds the client by runtime type lookup and builds the reflection request builder, so you must reference the opt-in Refit.Reflection package. .NET Framework has no trimming or AOT, so this costs nothing there.

ForGenerated<T> and AddRefitGeneratedClient<T> need that registration. On .NET Framework they throw unless you register the factory yourself with RegisterGeneratedFactory<T> / RegisterGeneratedSettingsFactory<T> at startup.

Generated-only client creation

For Native AoT or trimmed apps, RestService.ForGenerated<T> creates a client only when the generator registered an implementation for that interface:

csharp
using var client = new HttpClient
{
    BaseAddress = new Uri("https://api.github.com")
};

var api = RestService.ForGenerated<IGitHubApi>(client);

ForGenerated<T> never falls back to the reflection client. When the generated client builds every request directly, Refit skips the reflection request builder too. If no generated implementation is registered, it throws an InvalidOperationException pointing back to source generation setup.

Generated request building

By default the generator builds requests directly. Instead of a method body that calls the reflective pipeline through BuildRestResultFuncForMethod, the generated client creates the HttpRequestMessage, applies headers, properties, and body, then dispatches it through Refit's runtime helpers.

This cuts runtime reflection, metadata lookup, argument boxing, and delegate construction. It covers most request shapes:

  • parameters that appear in the path template
  • query parameters: auto-appended, [AliasAs], [Query] (including Format and CollectionFormat), scalar collections, [QueryName] flags and [Encoded] values
  • implicit [Body] detection on POST/PUT/PATCH
  • static [Headers]
  • dynamic [Header] parameters
  • [HeaderCollection] dictionaries
  • [Body] content
  • [Multipart] form uploads whose parts are StreamPart/ByteArrayPart/FileInfoPart (or a MultipartItem subclass), Stream, string, FileInfo, byte[], HttpContent, a date/time or Guid value, or an enumerable of these (an object part serialized through the content serializer still falls back to the runtime builder)
  • [Property] parameters
  • [Property] interface properties
  • cancellation tokens
  • Task, Task<T>, `Task<ApiResponse<

Issues· 4 open

View all issuesOpen on GitHub
  • #1667

    Dependency Dashboard

    Updated Sep 29, 2026

> Tags

C#c-sharpdotnetdotnet-corehttp

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 29, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言