SHARE:

Building a typed Httpclient with Refit in ASP.NET Core 3

What is Refit?

Refit is an automatic type-safe REST library for .NET Core, Xamarin and .NET. Refit turns your REST API into a live interface.

Installation and configuration

You just need to install that package on NuGet:

Install-Package Refit.HttpClientFactory

Usage Scenario

In this article I will show you a real life example: You are developing a microservices that consumes another microservice. The microservice to consume exposes CRUD operations on certain entity, in my exemple “Country”.

Let’s take a look at the API we want to call with a typed HttpClient:

How can we build easily typed HttpClient? With Refit definitely!

Refit will make you write less code. Let’s start to write the interface that Refit needs to make its Http calls:

It’s really easy to use, you build an interface, add required attributes (there is an attribute for each verb), add the required parameters for the Http Call and that’s it!. Note that there are many options, if you want more examples you can chaeck the documentation here: https://reactiveui.github.io/refit/ , you can for example add headers with the “header” attribute and much more….

Let’s configuration our type HttpClient in Startup.cs:

Refit exposes an extension method named AddRefitClient that return IHttpClientBuilder, because that, we are able now to build a typed HttpClient. Refit benefits from all advantages of IHttpClientFactory described here: http://anthonygiretti.com/2019/03/26/best-practices-with-httpclient-and-retry-policies-with-polly-in-net-core-2-part-1/

Let’s take a simple example, let’s configure the Url only.

You can definitely add a DelegateHandler, a Retry Policy with Polly (example here: http://anthonygiretti.com/2019/03/26/best-practices-with-httpclient-and-retry-policies-with-polly-in-net-core-2-part-2/ ).

Now we just need a last thing: inject ICountryRepository by injection dependency anywhere and call its methods, for example in a service:

I really recommand you to install it and test it! it’s very practical 😉

Written by

anthonygiretti

Anthony is a specialist in Web technologies (14 years of experience), in particular Microsoft .NET and learns the Cloud Azure platform. He has received twice the Microsoft MVP award and he is also certified Microsoft MCSD and Azure Fundamentals.