HttpResponseMessage에서 컨텐츠 / 메시지 가져 오기 = await

HttpResponseMessage의 내용을 얻으려고합니다. 이어야 {"message":"Action '' does not exist!","success":false}하지만 HttpResponseMessage에서 가져 오는 방법을 모르겠습니다.

HttpClient httpClient = new HttpClient();
HttpResponseMessage response = await httpClient.GetAsync("http://****?action=");
txtBlock.Text = Convert.ToString(response); //wrong!

이 경우 txtBlock의 값은 다음과 같습니다.

StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
  Vary: Accept-Encoding
  Keep-Alive: timeout=15, max=100
  Connection: Keep-Alive
  Date: Wed, 10 Apr 2013 20:46:37 GMT
  Server: Apache/2.2.16
  Server: (Debian)
  X-Powered-By: PHP/5.3.3-7+squeeze14
  Content-Length: 55
  Content-Type: text/html
}


답변

GetResponse () 를 호출해야합니다 .

Stream receiveStream = response.GetResponseStream ();
StreamReader readStream = new StreamReader (receiveStream, Encoding.UTF8);
txtBlock.Text = readStream.ReadToEnd();

답변

가장 쉬운 방법은 마지막 줄을 변경하는 것입니다.

txtBlock.Text = await response.Content.ReadAsStringAsync(); //right!

이 방법으로 스트림 리더를 소개 할 필요가 없으며 확장 방법이 필요하지 않습니다.


답변

다음과 같이 확장 방법을 만들 수 있습니다.

    public static string ContentToString(this HttpContent httpContent)
    {
        var readAsStringAsync = httpContent.ReadAsStringAsync();
        return readAsStringAsync.Result;
    }

그런 다음 간단하게 확장 메소드를 호출하십시오.

txtBlock.Text = response.Content.ContentToString();

나는 이것이 당신에게 도움이되기를 바랍니다 😉


답변

특정 유형 (예 : 테스트 내)으로 캐스팅하려면 ReadAsAsync 확장 방법을 사용할 수 있습니다 .

object yourTypeInstance = await response.Content.ReadAsAsync(typeof(YourType));

또는 동기 코드의 경우 다음을 수행하십시오.

object yourTypeInstance = response.Content.ReadAsAsync(typeof(YourType)).Result;

업데이트 : ReadAsAsync <> 의 일반 옵션도 있습니다.이 옵션 은 객체 선언 인스턴스 대신 특정 유형 인스턴스를 반환합니다.

YourType yourTypeInstance = await response.Content.ReadAsAsync<YourType>();

답변

rudivonstaden의 답변으로

`txtBlock.Text = await response.Content.ReadAsStringAsync();`

그러나 메소드를 비동기로 만들고 싶지 않으면 사용할 수 있습니다.

`txtBlock.Text = response.Content.ReadAsStringAsync();
 txtBlock.Text.Wait();`

Wait () 중요합니다. 비동기 작업을 수행하기 때문에 작업을 완료하기 전에 기다려야합니다.


답변

내가 제안하는 빠른 대답은 다음과 같습니다.

response.Result.Content.ReadAsStringAsync().Result


답변

다음 이미지 T는 반환 유형으로 와야하는 사람들에게 도움이된다고 생각합니다 .