Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

c# - 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...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...