August 27 2024
dotnet add package Refit.HttpClientFactory
using Refit;
using System.Threading.Tasks;
public interface IGitHubApi
{
[Get("/users/{username}")]
Task<GitHubUser> GetUserAsync(string username);
}
public class GitHubUser
{
public string Login { get; set; };
public string Name { get; set; };
public string Company { get; set; };
public int Followers { get; set; };
public int Following { get; set; };
public string AvatarUrl { get; set; };
}
builder.Services.AddRefitClient<IGitHubApi>()
.ConfigureHttpClient((sp, client) =>
{
var settings = sp.GetRequiredService<IOptions<GitHubSettings>().Value;
client.BaseAddress = new Uri(settings.BaseAddress);
client.DefaultRequestHeaders.Add("Authorization", settings.AccessToken);
client.DefaultRequestHeaders.Add("User-Agent", settings.UserAgent);
});
var user = await gitHubService.GetUserAsync("StefanTheCode");
public class GitHubApiClient : IGitHubApi
{
private readonly HttpClient _httpClient;
public GitHubApiClient(HttpClient httpClient)
{
_httpClient = httpClient;
_httpClient.BaseAddress = new Uri("https://api.github.com");
}
public async Task<GitHubUser> GetUserAsync(string username)
{
var response = await _httpClient.GetAsync($"/users/{username}");
response.EnsureSuccessStatusCode();
var user = await response.Content.ReadFromJsonAsync<GitHubUser>();
return user;
}
}
Join 13,250+ subscribers to improve your .NET Knowledge.
Go-to resource for understanding the core concepts of design patterns without the overwhelming complexity. In this concise and affordable ebook, I've distilled the essence of design patterns into an easy-to-digest format. It is a Beginner level. Check out it here.
Every Monday morning, I share 1 actionable tip on C#, .NET & Arcitecture topic, that you can use right away.
Subscribe to the TheCodeMan.net and be among the 13,250+ subscribers gaining practical tips and resources to enhance your .NET expertise.