gpt4 book ai didi

c# - 将异步任务响应转换为字符串

转载 作者:太空宇宙 更新时间:2023-11-03 23:04:53 25 4
gpt4 key购买 nike

首先,我想说,我是 C# 的新手。

我正在尝试创建一个 POST 请求,该请求将一些数据发送到不同服务器上某处的 PHP 文件。

现在,请求发送后我想看到响应,因为我从服务器发回一个 JSON 字符串作为成功消息。

当我使用下面的代码时:

public MainPage()
{

this.InitializeComponent();
Windows.UI.ViewManagement.ApplicationView.GetForCurrentView().SetDesiredBoundsMode(Windows.UI.ViewManagement.ApplicationViewBoundsMode.UseCoreWindow);

responseBlockTxt.Text = start();
}

public string start()
{
var response = sendRequest();

System.Diagnostics.Debug.WriteLine(response);

return "";
}

public async Task<string> sendRequest()
{
using (var client = new HttpClient())
{
var values = new Dictionary<string, string>
{
{ "vote", "true" },
{ "slug", "the-slug" }
};

var content = new FormUrlEncodedContent(values);

var response = await client.PostAsync("URL/api.php", content);

var responseString = await response.Content.ReadAsStringAsync();

return responseString;
}

}

输出是:

System.Threading.Tasks.Task`1[System.String]

那么,我如何才能看到所有的结果呢?

最佳答案

一路走异步。调用异步方法时避免阻塞调用。 async void 允许在事件处理程序中更新页面以执行加载事件调用

继续阅读 Async/Await - Best Practices in Asynchronous Programming

然后相应地更新你的代码

public MainPage() {    
this.InitializeComponent();
Windows.UI.ViewManagement.ApplicationView.GetForCurrentView().SetDesiredBoundsMode(Windows.UI.ViewManagement.ApplicationViewBoundsMode.UseCoreWindow);
this.Loaded += OnLoaded;
}

public async void OnLoaded(object sender, RoutedEventArgs e) {
responseBlockTxt.Text = await start();
}

public async Task<string> start() {
var response = await sendRequest();

System.Diagnostics.Debug.WriteLine(response);

return response;
}

private static HttpClient client = new HttpClient();

public async Task<string> sendRequest() {
var values = new Dictionary<string, string> {
{ "vote", "true" },
{ "slug", "the-slug" }
};

var content = new FormUrlEncodedContent(values);
using(var response = await client.PostAsync("URL/api.php", content)) {
var responseString = await response.Content.ReadAsStringAsync();
return responseString;
}
}

关于c# - 将异步任务响应转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41661683/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com