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

Ren*_*zzs 57 .net c# asp.net-mvc json httpclient

情况就是这样:

他们是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;
Run Code Online (Sandbox Code Playgroud)

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

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

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

是否有可能在客户端解决这个问题,还是Servoy Web服务?

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

Mag*_*ing 89

请尝试使用ReadAsStringAsync().

 var foo = resp.Content.ReadAsStringAsync().Result;
Run Code Online (Sandbox Code Playgroud)

为什么它的原因ReadAsAsync<string>()不工作是因为ReadAsAsync<>将尝试使用默认的一个MediaTypeFormatter(即JsonMediaTypeFormatter,XmlMediaTypeFormatter...)读取与内容content-typetext/plain.然而,没有默认格式化可以读取text/plain(他们只能读application/json,application/xml等等).

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

  • Quanda:您可以使用return JsonConvert.DeserializeObject &lt;Int32&gt;(resultString);,结果String是ReadAsStringAsync()之后的结果,JsonConvert来自Newtonsoft.Json。您可以从NuGet下载该库。这对于可移植库也非常有用,不仅适用于Int32,而且几乎适用于所有类型或类。 (3认同)
  • 我遇到了同样的问题,除了错误消息是""没有MediaTypeFormatter可用于从媒体类型为'text/html'的内容中读取'Int32'类型的对象." `int32有类似的解决方案吗? (2认同)

Zam*_*tic 6

我知道这是一个较旧的问题,但我觉得t3chb0t的答案引导我找到了最佳路径,并且想分享。您甚至不需要实现所有格式化程序的方法。我对我使用的 API 返回的内容类型“application/vnd.api+json”执行了以下操作:

public class VndApiJsonMediaTypeFormatter : JsonMediaTypeFormatter
{
    public VndApiJsonMediaTypeFormatter()
    {
        SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/vnd.api+json"));
    }
}
Run Code Online (Sandbox Code Playgroud)

可以像下面这样简单地使用:

HttpClient httpClient = new HttpClient("http://api.someaddress.com/");
HttpResponseMessage response = await httpClient.GetAsync("person");

List<System.Net.Http.Formatting.MediaTypeFormatter> formatters = new List<System.Net.Http.Formatting.MediaTypeFormatter>();
formatters.Add(new System.Net.Http.Formatting.JsonMediaTypeFormatter());
formatters.Add(new VndApiJsonMediaTypeFormatter());

var responseObject = await response.Content.ReadAsAsync<Person>(formatters);
Run Code Online (Sandbox Code Playgroud)

超级简单并且完全按照我的预期工作。


t3c*_*b0t 5

或者您可以创建自己的MediaTypeFormatter. 我用这个text/html。如果你添加text/plain它,它也会为你工作:

public class TextMediaTypeFormatter : MediaTypeFormatter
{
    public TextMediaTypeFormatter()
    {
        SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
    }

    public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
    {
        return ReadFromStreamAsync(type, readStream, content, formatterLogger, CancellationToken.None);
    }

    public override async Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger, CancellationToken cancellationToken)
    {
        using (var streamReader = new StreamReader(readStream))
        {
            return await streamReader.ReadToEndAsync();
        }
    }

    public override bool CanReadType(Type type)
    {
        return type == typeof(string);
    }

    public override bool CanWriteType(Type type)
    {
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

最后,您必须将其分配给HttpMethodContext.ResponseFormatter属性。