Getting content/message from HttpResponseMessage

后端 未结 8 2170
抹茶落季
抹茶落季 2020-12-01 00:18

I\'m trying to get content of HttpResponseMessage. It should be: {\"message\":\"Action \'\' does not exist!\",\"success\":false}, but I don\'t know, how to get

相关标签:
8条回答
  • 2020-12-01 00:56

    You need to call GetResponse().

    Stream receiveStream = response.GetResponseStream ();
    StreamReader readStream = new StreamReader (receiveStream, Encoding.UTF8);
    txtBlock.Text = readStream.ReadToEnd();
    
    0 讨论(0)
  • 2020-12-01 01:01

    The quick answer I suggest is:

    response.Result.Content.ReadAsStringAsync().Result

    0 讨论(0)
  • 2020-12-01 01:03

    I think the easiest approach is just to change the last line to

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

    This way you don't need to introduce any stream readers and you don't need any extension methods.

    0 讨论(0)
  • 2020-12-01 01:03

    If you want to cast it to specific type (e.g. within tests) you can use ReadAsAsync extension method:

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

    or following for synchronous code:

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

    Update: there is also generic option of ReadAsAsync<> which returns specific type instance instead of object-declared one:

    YourType yourTypeInstance = await response.Content.ReadAsAsync<YourType>();
    
    0 讨论(0)
  • 2020-12-01 01:05

    You can use the GetStringAsync method:

    var uri = new Uri("http://yoururlhere");
    var response = await client.GetStringAsync(uri);
    
    0 讨论(0)
  • 2020-12-01 01:07

    Try this, you can create an extension method like this:

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

    and then, simple call the extension method:

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

    I hope this help you ;-)

    0 讨论(0)
提交回复
热议问题