将类从MVC传递到Web API

joh*_*ohn 5 c# asp.net-mvc asp.net-web-api

在Web API方面,我有一个这样的客户类

public class CustomerAPI
{  
    public string CustomerName { get; set; }
    public string CustomerCity { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

在MVC方面,我有一个这样的客户类

public class CustomerMVC
{
    public string CustomerName { get; set; }
    public string CustomerCity{ get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我在ASP.Net MVC4中使用Web API服务,如下所示:

 var task = client.GetAsync("api/values")
                  .ContinueWith((taskwithresponse) =>
                    {
                        var response = taskwithresponse.Result;
                        var readtask = response.Content.ReadAsAsync<IEnumerable<CustomerMVC>>();

                        readtask.Wait();
                        serviceList = readtask.Result.ToList();
                    });
 task.Wait();  
Run Code Online (Sandbox Code Playgroud)

我这样做会遇到总体异常,如何转换CustomerWebAPICustomerMVC.

Jam*_*mes 5

将代码分开可能会有所帮助.我还建议使用Newtonsoft.Json nuget包进行序列化.

var task = client.GetAsync("api/values").Result;
//get results as a string
var result = task.Content.ReadAsStringAsync().Result;
//serialize to an object using Newtonsoft.Json nuget package
var customer = JsonConvert.DeserializeObject<CustomerMVC>(result);
Run Code Online (Sandbox Code Playgroud)

如果你想让它异步,你可以使用C#5中的async和await关键字:

public async Task<CustomerMVC> GetCustomer()
{
    //return control to caller until GetAsync has completed
    var task = await client.GetAsync("api/values");
    //return control to caller until ReadAsStringAsync has completed
    var result = await task.Content.ReadAsStringAsync()
    return JsonConvert.DeserializeObject<CustomerMVC>(result);
}
Run Code Online (Sandbox Code Playgroud)