Asp.net mvc 4 从.NET控制台应用程序使用Web API

Asp.net mvc 4 从.NET控制台应用程序使用Web API,asp.net-mvc-4,asp.net-web-api,console-application,Asp.net Mvc 4,Asp.net Web Api,Console Application,从.NET4.5控制台应用程序中使用MVC4.0WebAPI时,我遇到以下错误。 “没有MediaTypeFormatter可用于从媒体类型为“text/html”的内容中读取类型为“IEnumerable`1”的对象。” 请帮忙! 下面是我的代码: HttpClient client = new HttpClient(); client.BaseAddress = new Uri("http://localhost:30151/"); client.Defau

从.NET4.5控制台应用程序中使用MVC4.0WebAPI时,我遇到以下错误。 “没有MediaTypeFormatter可用于从媒体类型为“text/html”的内容中读取类型为“IEnumerable`1”的对象。” 请帮忙! 下面是我的代码:

HttpClient client = new HttpClient();
        client.BaseAddress = new Uri("http://localhost:30151/");

        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        //List all Customers
        HttpResponseMessage response = client.GetAsync("api/customers").Result;

         if (response.IsSuccessStatusCode)
        {
            var customers = response.Content.ReadAsAsync<IEnumerable<Customer>>().Result;
            foreach (var c in customers)
            {
                Console.WriteLine("ID: {0}\tName: {1}\tAddress: {2}\tEmail: {3}\tPhone: {4}", c.id, c.name, c.address, c.email, c.phone);
            }
        }
        else
        {
            Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
        }

        Console.Read();
HttpClient=newhttpclient();
client.BaseAddress=新Uri(“http://localhost:30151/");
client.DefaultRequestHeaders.Accept.Add(新的MediaTypeWithQualityHeaderValue(“应用程序/json”);
//列出所有客户
HttpResponseMessage response=client.GetAsync(“api/customers”).Result;
if(响应。IsSuccessStatusCode)
{
var customers=response.Content.ReadAsAsync().Result;
foreach(客户中的var c)
{
Console.WriteLine(“ID:{0}\t名称:{1}\t地址:{2}\t邮件:{3}\t电话:{4}”、c.ID、c.name、c.address、c.email、c.phone);
}
}
其他的
{
Console.WriteLine(“{0}({1})”,(int)response.StatusCode,response.ReasonPhrase);
}
Console.Read();

确保将发布数据的内容类型设置为“application/json”,如果内容类型为“text/html”,服务器将无法正确解释

Content-Type: application/json

你的客户端代码看起来不错。我怀疑服务器没有返回它应该返回的内容。使用fiddler实际查看服务器返回的内容