Renzzs Renzzs - 5 months ago 27
JSON Question

No MediaTypeFormatter is available to read an object of type 'String' from content with media type 'text/plain'

This is the situation:

Their is a external webservice in Servoy and I want to use this service in a ASP.NET MVC applicatie.

With this code I attempt to get the data from the service:

HttpResponseMessage resp = client.GetAsync("http://localhost:8080/servoy-service/iTechWebService/axws/shop/_authenticate/mp/112818142456/82cf1988197027955a679467c309274c4b").Result;
resp.EnsureSuccessStatusCode();

var foo = resp.Content.ReadAsAsync<string>().Result;


but when I run the application I get the next error:


No MediaTypeFormatter is available to read an object of type 'String'
from content with media type 'text/plain'.


If I open Fiddler and run the same url, I see the right data but the content-type is text/plain. However I see in Fiddler also the JSON that I want...

Is it possible to solve this at client side or is it the Servoy webservice?

Update:

Used HttpWebRequest instead of HttpResponseMessage and read the response with StreamReader...

Answer

Try using ReadAsStringAsync() instead.

 var foo = resp.Content.ReadAsStringAsync().Result;

The reason why it ReadAsAsync<string>() doesn't work is because ReadAsAsync<> will try to use one of the default MediaTypeFormatter (i.e. JsonMediaTypeFormatter, XmlMediaTypeFormatter, ...) to read the content with content-type of text/plain. However, none of the default formatter can read the text/plain (they can only read application/json, application/xml, etc).

By using ReadAsStringAsync(), the content will be read as string regardless of the content-type.

Comments