How to Use Refit in ASP.NET Core: with Example

Refit is a library that simplifies calling REST APIs by generating type-safe, strongly-typed HTTP client interfaces in C#. It allows developers to create API client code without writing explicit HTTP request handling code, reducing boilerplate and improving maintainability.
In this blog post, we’ll walk through the process of using Refit in an ASP.NET Core application, including how to set it up, create a service interface, and make API calls seamlessly.
What is Refit?
Refit is a REST library for .NET that helps you call REST APIs using C# interfaces. It automatically generates the code to make HTTP requests, deserialize responses, and handle the complexity behind the scenes. This way, you don’t have to manually write HTTP client code — define an interface, and Refit takes care of the rest.
Benefits of Using Refit:
Less boilerplate: Automatically handles HTTP request creation, serialization, and deserialization.
Type safety: Strongly-typed requests and responses prevent errors and improve code clarity.
Easy to integrate: Seamlessly integrates with ASP.NET Core DI (dependency injection).
Supports modern .NET features: Works well with async/await, HTTPClientFactory, and other common patterns in ASP.NET Core.
Step 1: Install Refit
First, you need to install the Refit NuGet package. In your ASP.NET Core project, open the Package Manager Console or edit your .csproj file to add the following:
Install-Package Refit
Using .NET CLI:
dotnet add package Refit
Step 2: Create a Refit Interface
Refit uses C# interfaces to define the structure of API calls. The interface methods map directly to HTTP methods like GET, POST, PUT, and DELETE.
Let’s say we are building a simple client to interact with a public API. For this example, we’ll use the JSONPlaceholder API, a free fake API for testing and prototyping. We’ll define an interface to fetch posts.
Define an API Interface
Create a new folder called Services in your project, then add an interface IPostService.cs:
using Refit;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace YourApp.Services
{
public interface IPostService
{
[Get("/posts")]
Task<List<Post>> GetPostsAsync();
[Get("/posts/{id}")]
Task<Post> GetPostByIdAsync(int id);
[Post("/posts")]
Task<Post> CreatePostAsync([Body] Post newPost);
}
public class Post
{
public int Id { get; set; }
public string Title { get; set; }
public string Body { get; set; }
}
}
Here’s what’s happening in the interface:
- [Get(“/posts”)] — This attribute indicates a GET request to the /posts endpoint.
- [Get(“/posts/{id}”)] — A parameterized GET request to fetch a single post by id.
- [Post(“/posts”)] — A POST request to create a new post using the Post object in the request body.
In this example, we are using the Post class to represent the data we’re interacting with. Refit will automatically serialize and deserialize the object when making the request.
Step 3: Register Refit with Dependency Injection
ASP.NET Core uses Dependency Injection (DI) to manage service lifetimes and resolve dependencies. To use Refit’s API client in your controllers or other services, you need to register it in the DI container.
Open the Startup.cs or Program.cs file (depending on whether you’re using .NET 5 or later) and add the following code in the ConfigureServices method.
using Refit;
using YourApp.Services;
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// Register Refit client
services.AddRefitClient<IPostService>()
.ConfigureHttpClient(c => c.BaseAddress = new Uri("https://jsonplaceholder.typicode.com"));
// Register other services
services.AddControllersWithViews();
}
}
In this code:
- AddRefitClient<IPostService>(): Registers the IPostService interface for dependency injection.
- ConfigureHttpClient(): Configures the HttpClient with the base URL of the API (https://jsonplaceholder.typicode.com).
The AddRefitClient extension method simplifies the registration and creation of HTTP clients for Refit.
Step 4: Use Refit in a Controller or Service
Once the Refit client is registered, you can inject the IPostService interface into your controllers or services and make API calls.
Example Controller
Create a new controller, PostsController.cs, to use the Refit API client:
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Threading.Tasks;
using YourApp.Services;
namespace YourApp.Controllers
{
public class PostsController : Controller
{
private readonly IPostService _postService;
public PostsController(IPostService postService)
{
_postService = postService;
}
public async Task<IActionResult> Index()
{
List<Post> posts = await _postService.GetPostsAsync();
return View(posts);
}
public async Task<IActionResult> Details(int id)
{
Post post = await _postService.GetPostByIdAsync(id);
return View(post);
}
[HttpPost]
public async Task<IActionResult> Create(Post newPost)
{
if (ModelState.IsValid)
{
Post createdPost = await _postService.CreatePostAsync(newPost);
return RedirectToAction(nameof(Index));
}
return View(newPost);
}
}
}
Explanation:
- Index(): Fetches all posts by calling the GetPostsAsync() method from the IPostService.
- Details(): Fetches a single post by ID using the GetPostByIdAsync() method.
- Create(): Sends a new post to the API using the CreatePostAsync() method.
Views
For simplicity, let’s assume you have basic Razor views like Index.cshtml and Details.cshtml to display the posts. You can customize these views according to your project’s needs.
Step 5: Test the Application
Once you’ve set up the controller and views, run the application, navigate to the /Posts route, and test the following:
- Fetching all posts from the Index view.
- Viewing a single post by clicking on the post title (which takes you to the Details view).
- Creating a new post using a simple form (for example, POST to /Posts/Create).
Example Output:
When you navigate to /Posts, you should see a list of posts fetched from the JSONPlaceholder API. If you visit a post’s details page, you should see the details of that post.
Conclusion
Refit is a great library for simplifying HTTP API calls in ASP.NET Core. By defining a clean, strongly-typed interface for your API interactions, you can focus on business logic while avoiding the repetitive and error-prone task of manually creating HTTP request code.
Key Takeaways:
- Refit helps reduce boilerplate code by automatically handling HTTP requests, serialization, and deserialization.
- You define the API interface using attributes like [Get], [Post], etc., which Refit uses to generate the necessary HTTP client code.
- It integrates seamlessly with ASP.NET Core’s dependency injection system for easy and efficient service management.
Refit makes API integration simpler and more maintainable, especially when working with RESTful APIs in ASP.NET Core applications.
Do you have any questions or need further clarification on how to use Refit in your ASP.NET Core app? Let me know!