簡體   English   中英

異步POST請求到php服務器

[英]async POST request to php server

我正在嘗試從我的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;

在最后一行中調用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/zh-cn/dotnet/standard/microservices-architecture/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM