我搜索了很多,但没有找到任何使用存储库模式在 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在哪里/如何获取 Newtonsoft.Json
包。
另一种选择是重用 HttpClient
对象并使您的存储库成为 IDisposable
,因为您需要在使用完 HttpClient
后释放它。在我的第一个示例中,它发生在 using
语句末尾的 HttpClient
使用之后。
关于c# - 通过 HttpClient 使用外部 REST Web 服务的存储库模式示例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38379360/