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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12512483/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 23:30:26  来源:igfitidea点击:

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

c#.netasp.net-mvcjsonhttpclient

提问by Renzzs

This is the situation:

情况是这样的:

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

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

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'.

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

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

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

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

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

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

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

采纳答案by Maggie Ying

Try using ReadAsStringAsync() instead.

尝试改用 ReadAsStringAsync()。

 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-typeof text/plain. However, none of the default formatter can read the text/plain(they can only read application/json, application/xml, etc).

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

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

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

回答by t3chb0t

Or you can just create your own MediaTypeFormatter. I use this for text/html. If you add text/plainto it, it'll work for you too:

或者您可以创建自己的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;
    }
}

Finally you have to assign this to the HttpMethodContext.ResponseFormatterproperty.

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