DotNETWeekly-io / DotNetWeekly

DotNet weekly newsletter
MIT License
198 stars 3 forks source link

【文章推荐】Refit.NET个人实践 #664

Closed tonyqus closed 2 weeks ago

tonyqus commented 1 month ago

https://medium.com/medialesson/refit-net-my-personal-caller-best-practise-5e0b24ed6486

gaufung commented 4 weeks ago

image

Refit.NET 中比较著名的开源库。文章作者分享了自己在使用 Refit 的一些最佳实践。主要是不通过直接定义的接口来使用它,而是将它封装成另外一个服务,这样可以做额外的工作,比如认证,授权和异常处理。

public interface IMyHttpApiClient 
{
    [Get("/users/{username}/repos")]
    Task<List<Repository>> GetUserRepositoriesAsync(string username);
}

// Creating a Refit client
IMyHttpApiClient  gitHubApi = RestService.For<IMyHttpApiClient >("https://api.github.com");

public class MyApiProvider(IMyHttpApiClient Client)
{
    public Task<UserResponseItem> GetUser(string user)
    {
        return Execute(() => Client.GetUser(user));
    }
}