Share via


C# How to use HttpClient await client.PostAsync to return string

Question

Saturday, July 14, 2018 6:50 PM

Hello,

I tried to rewrite a C# HttpClient program from this GITHUB C# REST Client Sample.

https://github.com/dotnet/samples/tree/master/csharp/getting-started/console-webapiclient

The following is Program.cs: (I don’t need the repo.cs)

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace WebAPIClient
{
class Program
{
private static readonly HttpClient client = new HttpClient();

static void Main(string[] args)
{
var token1 = SessinToken();
Console.WriteLine("Done get session token");
}

private static async Task<string> SessinToken()
{
string Login_URL1 = "https://www.webserver1.com/api/login";
string Login_Data1 = "username=abc&password=abc123";
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var Pay_Load1 = new StringContent(Login_Data1, Encoding.UTF8, "application/x-www-form-urlencoded");
var response = await client.PostAsync(Login_URL1, Pay_Load1);
return await response.Content.ReadAsStringAsync();
}
}
}

In order to browse the webserver1.com, first I have to use HTTP POST send a payload string (username=XXX&password=YYYYYYY) using "application/x-www-form-urlencoded" format, then I should receive a string from the webserver1.com, which contains a session token value in JSon format.  To make things easy to understand, I just want to return the string from the web server’s response.

The code got complied, but when I run it, I can see the returned token1 value is some thing like:

token1 Id = 5, Status = WaitingForActivation, Method = "{null}", Result = "{Not yet computed}"

System.Threading.Tasks.Task<string>

It seems the session token is not returned yet.  

If I use Rest Client like Insomnia to get the session token using the same HTTP POST, it will take 1 or 2 seconds to get the session token, not very quick, but it is awaitable.  However, using the above code, I never get any returned response.

The console application type is: Microsoft.NetCore.App(1.0.5); I installed .Net Core using this program: dotnet-sdk-2.1.302-win-gs-x64.exe downloaded from this URL:

https://download.microsoft.com/download/4/0/9/40920432-3302-47a8-b13c-bbc4848ad114/dotnet-sdk-2.1.302-win-gs-x64.exe

Any suggestion?

All replies (3)

Monday, July 16, 2018 3:13 AM

You have declared "SessinToken" as returning a Task<string>, but that's not right.   You are doing an "await" in the return statement, which means the function actually returns a plain old "string".  Your "token1" variable is getting a task which is never going to run.

Tim Roberts | Driver MVP Emeritus | Providenza & Boekelheide, Inc.


Monday, July 16, 2018 9:09 AM

Hello:

I understand my mistake now, but I don't how to change it.

Can you advice?

Thanks,


Saturday, January 4, 2020 7:34 AM

You could try using RestClient.Net

This is an example of how to make a GetAsync call to return JSON (string)

var client = new Client(new NewtonsoftSerializationAdapter(), new Uri("https://restcountries.eu/rest/v2/name/australia"));
var json = await client.GetAsync<string>();

Code Reference

Here is a Post example which can be used in the same way. Just specify string in the TResponseBody type argument.

Here is a Post example:

await client.PostAsync<string, UserPost>(requestUserPost, "/posts");

Code Reference

Client uses HttpClient under the hood here so you can look at how it is doing it.