How to read HttpResponseMessage content as text

后端 未结 3 2052
攒了一身酷
攒了一身酷 2021-01-01 09:00

I\'m using HttpResponseMessage class as a response from an AJAX call which is returning JSON data from a service. When I pause execution after the AJAX call comes back from

相关标签:
3条回答
  • 2021-01-01 09:10

    The textual representation of the response is hidden in the Content property of the HttpResponseMessage class. Specifically, you get the response like this:

    response.Content.ReadAsStringAsync();

    Like all modern Async methods, ReadAsStringAsync returns a Task. To get the result directly, use the Result property of the task:

    response.Content.ReadAsStringAsync().Result;

    Note that Result is blocking. You can also await ReadAsStringAsync().

    0 讨论(0)
  • 2021-01-01 09:19

    You can you ReadAsStringAsync() method

    var result = await response.Content.ReadAsStringAsync();
    

    We need to use await because we are using ReadAsStringAsync() which return task.

    0 讨论(0)
  • 2021-01-01 09:24

    You can use ReadAsStringAsync on the Content.

    var response = await client.SendAsync(request);
    var content = await response.Content.ReadAsStringAsync();
    

    Note that you usually should be using await - not .Result.

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