简体   繁体   中英

async POST request to php server

I am trying to send a string from my C# app to my php server (first time using async). When I try to write out my response to the console, I just get this: System.Threading.Tasks.Task'1[System.String]

C# Code

private HttpClient request;
public async Task<string> licenseCheck(HttpClient client, string email){
var payload = new Dictionary<string, string>
{
    { "email", email }
};

var content = new FormUrlEncodedContent(payload);           
var response = await client.PostAsync("https://example.io/checkin.php", content);

return await response.Content.ReadAsStringAsync();
}

request = new HttpClient();
Console.WriteLine(licenseCheck(request,"joe@example.com").ToString());

PHP Code - checkin.php

<?php
    $email = trim(strtolower($_POST['email']));
    header('Content-Type: application/x-www-form-urlencoded');
    echo $email;

The object that you're calling ToString() on in the last line is the Task that performs the license check. You should be awaiting the call to licenseCheck, or using the Task.Result property to synchronously wait on the task and get the result if your request is running synchronously:

// This allows the runtime to use this thread to do other work while it waits for the license check to finish, when it will then resume running your code
Console.WriteLine(await licenseCheck(request,"joe@example.com"));
// This causes the thread to twiddle its thumbs and wait until the license check finishes, then continue
Console.WriteLine(licenseCheck(request,"joe@example.com").Result);

Also consider using HttpClientFactory if you're running on .NET Core:

https://docs.microsoft.com/en-us/dotnet/standard/microservices-architecture/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM