your programing

미디어 유형이 'text / plain'인 콘텐츠에서 'String'유형의 개체를 읽는 데 사용할 수있는 MediaTypeFormatter가 없습니다.

lovepro 2020. 12. 30. 19:50
반응형

미디어 유형이 'text / plain'인 콘텐츠에서 'String'유형의 개체를 읽는 데 사용할 수있는 MediaTypeFormatter가 없습니다.


이것이 상황입니다.

Servoy 의 외부 웹 서비스이며 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;

하지만 응용 프로그램을 실행할 때 다음 오류가 발생합니다.

미디어 유형이 'text / plain'인 콘텐츠에서 'String'유형의 개체를 읽는 데 사용할 수있는 MediaTypeFormatter가 없습니다.

Fiddler를 열고 동일한 URL을 실행하면 올바른 데이터가 표시되지만 콘텐츠 유형은 text / plain입니다. 그러나 Fiddler에서 원하는 JSON도 볼 수 있습니다.

클라이언트 측에서이 문제를 해결할 수 있습니까 아니면 Servoy 웹 서비스입니까?

업데이트 :
HttpResponseMessage 대신 HttpWebRequest를 사용하고 StreamReader로 응답을 읽습니다.


대신 ReadAsStringAsync ()를 사용해보십시오.

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

ReadAsAsync<string>()작동하지 않는 이유 ReadAsAsync<>는 기본값 중 하나 MediaTypeFormatter(예 JsonMediaTypeFormatter: XmlMediaTypeFormatter, ...)를 사용하여의 내용을 읽으려고하기 때문 content-type입니다 text/plain. 그러나 기본 포맷 중 어느 것도 읽을 수 없다 text/plain(그들은 단지 읽을 수 있습니다 application/json, application/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속성 에 할당해야합니다 .

참조 URL : https://stackoverflow.com/questions/12512483/no-mediatypeformatter-is-available-to-read-an-object-of-type-string-from-conte

반응형