prosource

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

probook 2023. 3. 29. 21:36
반응형

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

상황이 이렇습니다.

서보이의 외부 웹 서비스이며 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을 실행하면 올바른 데이터가 표시되지만 content-type은 text/plain입니다.하지만 내가 원하는 JSON도 Fiddler에서 봤는데...

클라이언트 측에서 해결할 수 있습니까, 아니면 서보이 웹 서비스입니까?

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

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

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

그 이유ReadAsAsync<string>()동작하지 않는 것은ReadAsAsync<>디폴트 중 하나를 사용하려고 합니다.MediaTypeFormatter(즉,JsonMediaTypeFormatter,XmlMediaTypeFormatter, ...)를 사용하여 내용을 읽습니다.content-typetext/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소유물.

오래된 질문인 것은 알지만, 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);

매우 심플하고 기대했던 대로 작동합니다.

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

반응형