2

.NET 4.5 コンソール アプリから MVC 4.0 Web API を使用しているときに、次のエラーが発生します。「メディア タイプが 'text/html' のコンテンツからタイプ 'IEnumerable`1' のオブジェクトを読み取るために使用できる MediaTypeFormatter はありません。」助けてください!以下は私のコードです:

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();
4

2 に答える 2

0

クライアントコードは問題ないようです。サーバーが本来あるべきものを返していないと思われます。fiddler を使用して、サーバーから何が返されているかを実際に確認します。

于 2013-05-02T11:31:02.787 に答える
0

Make sure you are setting the content type of your posted data to 'application/json' If your content type is 'text/html' the server won't interpret it properly

Content-Type: application/json
于 2013-04-29T16:30:51.697 に答える