gpt4 book ai didi

c# - 没有 MediaTypeFormatter 可用于从媒体类型为 'String' 的内容中读取类型为 'text/plain' 的对象

转载 作者:IT老高 更新时间:2023-10-28 12:44:48 30 4
gpt4 key购买 nike

情况是这样的:

它们是 Servoy 中的外部 Web 服务,我想在 ASP.NET MVC 应用程序中使用此服务。

通过这段代码,我尝试从服务中获取数据:

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;

但是当我运行应用程序时,我得到了下一个错误:

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

如果我打开 Fiddler 并运行相同的 url,我会看到正确的数据,但内容类型是 text/plain。但是我在 Fiddler 中也看到了我想要的 JSON...

是否可以在客户端解决这个问题,或者是 Servoy 网络服务?

更新:
使用 HttpWebRequest 而不是 HttpResponseMessage 并使用 StreamReader 读取响应...

最佳答案

尝试改用 ReadAsStringAsync()。

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

它的原因ReadAsAsync<string>()不起作用是因为ReadAsAsync<>将尝试使用默认的 MediaTypeFormatter 之一(即 JsonMediaTypeFormatter , XmlMediaTypeFormatter , ...)用 content-type 阅读内容的 text/plain .但是,没有一个默认格式化程序可以读取 text/plain (他们只能阅读 application/jsonapplication/xml 等)。

通过使用 ReadAsStringAsync() ,无论内容类型如何,内容都将被读取为字符串。

关于c# - 没有 MediaTypeFormatter 可用于从媒体类型为 'String' 的内容中读取类型为 'text/plain' 的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12512483/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com