Using C# - How may I have the function return the response back to the main program?
I tried adding Task string to the function along with adding string response = cls.PostData(accesstoken, thejsondata).Wait(); to the call from Main. I am guessing I am not understanding the asynchronous aspect.
// From the main program
CallingClass cls = new CallingClass();
cls.PostData(accesstoken, thejsondata).Wait();
// want the "body" of data returned here?
public class CallingClass
{
private static readonly HttpClient client = new HttpClient();
public async Task PostData(string accesstoken, string thejsondata)
{
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri("https://whateverurl.com/"),
Headers =
{
{ "Authorization", accesstoken }
},
*/
Content = new StringContent(thejsondata))
{
Headers =
{
ContentType = new MediaTypeHeaderValue("application/json")
}
}
};
using (var response = await client.SendAsync(request))
{
response.EnsureSuccessStatusCode();
var body = await response.Content.ReadAsStringAsync();
Int32 responseStatusCode = (Int32)response.StatusCode;
if (responseStatusCode.ToString() == "200" || responseStatusCode.ToString() == "201")
{
hlp.AddToOutputFolder("StatusCode - " + responseStatusCode.ToString());
hlp.AddToOutputFolder("Response - " + body);
}
else
{
hlp.AddToOutputFolder("ERROR RESPONSE STRING= " + responseStatusCode.ToString());
}
//return body;
}
}
}