通过HttpClient使用外部REST Web服务的存储库模式示例? [英] Examples of Repository Pattern with consuming an external REST web service via HttpClient?

查看:74
本文介绍了通过HttpClient使用外部REST Web服务的存储库模式示例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've searched around quite a bit, but haven't found any good examples of consuming an external REST web service using a Repository Pattern in something like an ASP.NET MVC app, with loose coupling and meaningful separation of concerns. Almost all examples of repository pattern I find online are writing SQL data or using an ORM. I'd just like to see some examples of retrieving data using HttpClient but wrapped in a repository.

有没有引用好的例子?还是有人可以写一个简单的例子?

Any references to good examples? Or could someone write up a simple example?

推荐答案

一个简单的示例:

// 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 async Task<string> GetStringAsync(string url)
    {
        using (var httpClient = new HttpClient())
        {
            return await httpClient.GetStringAsync(url);
        }
    }
}

此处是在何处/如何获取Newtonsoft.Json软件包.

Here is where/how to get Newtonsoft.Json package.

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

Another option would be to reuse HttpClient object and make your repository IDisposable because you need to dispose HttpClient when you done working with it. In my first example it happens right after HttpClient usage at the end of using statement.

这篇关于通过HttpClient使用外部REST Web服务的存储库模式示例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆