| Muhammad Waseem

About Newsletter
Books
30 .NET Tips
Sponsorship
Getting Started with Refit in .NET
Nov 27, 2023
3 min read

Getting Started with Refit in .NET

Sponsor this Newsletter

Recap of Refit

Refit is the automatic type-safe REST library for .NET Core, Xamarin and .NET.

It lets you define your API calls using C# interfaces in simple three steps.

public interface IGitHubApi
{
    [Get("/users/{user}")]
    Task<User> GetUser(string user);
}
string url = "https://api.github.com";
var gitHubApi = RestService.For<IGitHubApi>(url);
var octocat = await gitHubApi.GetUser("octocat");
services.AddRefitClient<IGitHubApi>()
    .ConfigureHttpClient(c => c.BaseAddress = new Uri(url));

That is not the target for today’s newsletter, if you are not aware about how to use Refit in .NET then check this article I wrote earlier :

Using Refit to Consume APIs in .NET Core

👉 What Are Query Attributes and How to Add Them?

When you pass parameters in the query string of a URL, the parameters are appended to the URL after a question mark (?), and each parameter is specified as a key-value pair. Multiple parameters are separated by an ampersand (&). The general syntax is as follows:

http://example.com/path/to/resource?parameter1=value1

We can achieve similar in refit like this :

[Post("/api/student/details")]
Task<GetStudentDetailResponse> GetStudentDetailAsync(
    [Query] int studentId,
    GetStudentDetailCommand command,
    CancellationToken cancellationToken = default);

Parameter with [Query] would be passed as a query string and the one in command would be passed in body.

If you wish to add multiple parameters then add them and just add [Query] before that.

👉 How to Properly Set the Content Type Header

Content headers are essential, we need to set them with each request. Let me show you how would I add that.

I prefer to make a delegating handler for it, here you can read about it :

HTTP Message Handlers in ASP.NET Web API

public class AddDefaultContentHeader : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, 
        CancellationToken cancellationToken)
    {
        request.Headers.Add("Accept", "application/json");
        return await base.SendAsync(request, cancellationToken);
    }
}
services.AddRefitClient<IStudentRefitApi>(refitSettings)
    .ConfigureHttpClient(configureClient)
    .AddHttpMessageHandler<AddDefaultContentHeader>();

👉 How to Add Bearer Token in Headers

Similarly I can create a delegating handler for adding bearer token.

public sealed class AddBearerTokenHeader : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, 
        CancellationToken cancellationToken)
    {
        string token = "som-token"; 
        string bearerToken = $"Bearer {token}";
        request.Headers.Add("Authorization", bearerToken);
        return await base.SendAsync(request, cancellationToken);
    }
}

We can register it similarly as we did with content header. Add this handler only with your secure APIs which need token for successful call.

This article was originally published at https://mwaseemzakir.substack.com/ on Nov 27, 2023 .

Whenever you're ready, there are 3 ways I can help you:

  1. Subscribe to my youtube channel : For in-depth tutorials, coding tips, and industry insights.
  2. Promote yourself to 9,000+ subscribers : By sponsoring this newsletter
  3. Patreon community : Get access to all of my blogs and articles at one place
Previous Next

Subscribe to Newsletter

Join 9,000 Software Engineers

Buy Me a Coffee

Enjoy my articles? Support me by buying a coffee!

Buy Me a Coffee

Muhammad Waseem

Resources
  • Books
  • Courses
Newsletter
  • Articles
  • Sponsorship
Books
  • 30 .NET Tips
  • 100 .NET Tips (Soon)
Author
  • About Us
  • Contact Us
Policy
  • Privacy Policy
  • Terms and Conditions
Interview
  • C# & .NET
  • Web API

Join my .NET newsletter and stay updated!

© 2025 Muhammad Waseem. All rights reserved.