WebAPI:HttpClient响应字符串模型绑定



如何将WebApi的json/xml响应绑定到模型类型?比如,如果我有一个模型User,并且我的api以json/xml格式返回用户列表,那么我如何自动将响应绑定到List<users>?在具有WebHttpBinding的WCF客户端中,一旦我们创建通道,我们就会获得对服务接口的引用,并可以调用RPC等方法和使用模型。

有了WebApi,我们能够以一种很好的方式处理响应。但我不知道如何自动将响应绑定或强制转换为User或List<User>这样的模型。

如果您的rest客户端是System.Net.Http.HttpClient:

        var result = new List<User>();
        var client = new HttpClient();
        client.GetAsync("http://sample.net/api/user/GetList").ContinueWith((task) =>
        {
            HttpResponseMessage response = task.Result;
                response.Content.ReadAsAsync<List<User>>().ContinueWith((readTask) =>
                {
                    result = readTask.Result;
                });
        }).Wait();

最新更新