【问题标题】:WebAPI: HttpClient response string model bindingWebAPI:HttpClient 响应字符串模型绑定
【发布时间】:2012-04-10 02:45:29
【问题描述】:

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

借助 WebApi,我们能够以异步方式处理响应,这很好。但我无法了解我们如何自动将响应绑定或强制转换为像 User 或 List<User> 这样的模型。

【问题讨论】:

    标签: wcf-rest wcf-web-api asp.net-web-api


    【解决方案1】:

    如果您的其余客户端是 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();
    

    【讨论】:

    • ReadAsAsync() 是一种扩展方法。您需要参考 System.Net.Http.Formatting。出于某种奇怪的原因,这并没有出现在我的系统参考列表中。我需要搜索“格式”才能显示它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-23
    • 1970-01-01
    • 2018-04-30
    • 1970-01-01
    • 2020-04-23
    相关资源
    最近更新 更多