Search code examples
c#asp.net-web-apisystem.net

How do I read (not write!) the content from System.Net.Http.StringContent?


Given the following code:

    using System.Net.Http;
    ...
    StringContent sc = New StringContent("Hello!");
    string myContent = ???;

What do I need to replace the ??? with in order to read the string value from sc, so that myContent = "Hello!"?

.ToString just returns System.String, as does .ReadAsStringAsync. How do I read out what I've written in?


Solution

  • You can use the ReadAsStringAsync() method, then get the result using an await statement or the Result property:

    StringContent sc = new StringContent("Hello!");
    
    string myContent = await sc.ReadAsStringAsync();
    //or
    string myContent = sc.ReadAsStringAsync().Result;