【问题标题】:async POST request to php server对 php 服务器的异步 POST 请求
【发布时间】:2019-04-20 03:48:22
【问题描述】:

我正在尝试将一个字符串从我的 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;

【问题讨论】:

  • 为什么你等待ReadAsStringAsync,但你不等待licenseCheck?简而言之:您不是在等待请求完成,而是在 Task&lt;string&gt; 对象上调用 .ToString()
  • 正如我所说,我是 async 的新手,很难理解它。大部分代码来自另一个 SO 帖子。
  • 好吧,要从async 方法中得到结果,你必须await 它,否则你得到Taskawait 会自动为你解包结果,解包错误等。
  • 请参阅this question,但请记住,如果可以的话,您确实从顶部(到异步方法调用)一直使用 async/await。请注意,从 C#7 开始,您可以将 async Task Main 作为应用程序的入口点。如果你想学习 async/await,我推荐 Stephen Cleary's blog(以及众多 Stack Overflow 答案)。

标签: c# php async-await


【解决方案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

【讨论】:

  • 通过添加 await 来更改我的 Console.WriteLine 似乎很简单。我的功能会改变吗?我刚刚尝试了Console.WriteLine(await licenseCheck(request,"joe@example.com"));,结果出现了一堆其他错误。我认为问题在于我的职能。已经为此工作了大约 9 个小时 :-)
  • 您只能在异步函数中使用 await 关键字。如果您尝试从 Main() 方法执行此操作,那么您只能在使用 c# 8 或更高版本时声明异步 Main。检查项目的配置。如果由于某种原因调用 licenseCheck 的函数不能是异步的,那么你需要使用 Task.Result
  • @James 你可以在 C# 7 中做到这一点。
  • 我的错;我通常记得它是“最新版本的 C#,VS 默认不选择它”。现在最新版本是 8.0,我搞混了。似乎该功能实际上是在 C# 7.1 中引入的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多