异步POST请求到php服务器

时间:2019-04-20 03:48:22

标签: c# php async-await

我正在尝试从C#应用程序向我的php服务器发送一个字符串(第一次使用异步)。当我尝试写出对控制台的响应时,我得到的是:System.Threading.Tasks.Task'1[System.String]

C#代码

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代码-checkin.php

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

1 个答案:

答案 0 :(得分:1)

在最后一行中调用ToString()的对象是执行许可证检查的任务。您应该等待对licenseCheck的调用,或者使用Task.Result属性同步等待任务并在请求同步运行时获取结果:

// 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);

如果您在.NET Core上运行,还可以考虑使用HttpClientFactory:

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