簡體   English   中英

沒有 MediaTypeFormatter 可用於從媒體類型為“text/plain”的內容中讀取“String”類型的對象

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

情況是這樣的:

他們是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;

但是當我運行應用程序時,我收到下一個錯誤:

沒有 MediaTypeFormatter 可用於從媒體類型為“text/plain”的內容中讀取“String”類型的對象。

如果我打開 Fiddler 並運行相同的 url,我會看到正確的數據,但內容類型是文本/純文本。 但是我在 Fiddler 中也看到了我想要的 JSON ......

是否可以在客戶端解決這個問題,或者是 Servoy 網絡服務?

更新:
使用 HttpWebRequest 而不是 HttpResponseMessage 並使用 StreamReader 讀取響應...

嘗試改用 ReadAsStringAsync()。

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

ReadAsAsync<string>()不起作用的原因是因為ReadAsAsync<>將嘗試使用默認的MediaTypeFormatter (即JsonMediaTypeFormatterXmlMediaTypeFormatter ,...)來讀取content-typetext/plain . 但是,沒有一個默認格式化程序可以讀取text/plain (它們只能讀取application/jsonapplication/xml等)。

通過使用ReadAsStringAsync() ,無論內容類型如何,內容都將被讀取為字符串。

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

最后,您必須將其分配給HttpMethodContext.ResponseFormatter屬性。

我知道這是一個較舊的問題,但我覺得t3chb0t的答案引向了最佳路徑,並且喜歡分享。 您甚至不需要實現所有格式化程序的方法。 我對我使用的 API 返回的內容類型“application/vnd.api+json”執行了以下操作:

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

可以簡單地使用如下:

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);

超級簡單,完全符合我的預期。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM