通过 HttpClient 使用外部 REST Web 服务的存储库模式示例?

Examples of Repository Pattern with consuming an external REST web service via HttpClient?

我搜索了很多,但没有找到任何使用存储库模式在 ASP.NET MVC 应用程序中使用松散耦合且有意义的外部 REST Web 服务的好例子关注点分离。我在网上找到的几乎所有存储库模式示例都在写入 SQL 数据或使用 ORM。我只想看一些使用 HttpClient 检索数据但包装在存储库中的示例。

有人可以写一个简单的例子吗?

一个简单的例子:

// You need interface to keep your repository usage abstracted
// from concrete implementation as this is the whole point of 
// repository pattern.
public interface IUserRepository
{
    Task<User> GetUserAsync(int userId);
}

public class UserRepository : IUserRepository
{
    private static string baseUrl = "https://example.com/api/"

    public async Task<User> GetUserAsync(int userId)
    {
        var userJson = await GetStringAsync(baseUrl + "users/" + userId);
        // Here I use Newtonsoft.Json to deserialize JSON string to User object
        var user = JsonConvert.DeserializeObject<User>(userJson);
        return user;
    }

    private static Task<string> GetStringAsync(string url)
    {
        using (var httpClient = new HttpClient())
        {
            return httpClient.GetStringAsync(url);
        }
    }
}

Here 是 where/how 得到 Newtonsoft.Json 包。


另一种选择是重用 HttpClient 对象并使您的存储库 IDisposable 因为您需要在完成使用后处置 HttpClient。在我的第一个示例中,它发生在 using 语句末尾的 HttpClient 使用之后。