将异步任务响应转换为字符串 [英] Converting async Task Response to String

查看:85
本文介绍了将异步任务响应转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

First of all, I would like to say, I'm quite new to C#.

我正在尝试创建一个POST请求,该请求会将一些数据发送到另一台服务器上某处的PHP文件中.

I'm trying to create a POST request which sends some data to a PHP file somewhere on a different server.

现在,发送请求后,我希望看到响应,因为我正在从服务器发送回JSON字符串作为成功消息.

Now, after the request is send I would like to see the response, as I'm sending back a JSON string from the server as a success message.

当我使用以下代码时:

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]

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

那么,我怎么看所有的结果呢?

So, how would I see all the results from this?

推荐答案

完全异步.避免在调用异步方法时阻塞调用.事件处理程序中允许 async void ,因此更新页面以执行加载事件调用

Go Async all the way. Avoid blocking calls when calling async methods. async void is allowed in event handlers so update page to perform the call on load event

请阅读异步/等待-异步编程的最佳做法

然后相应地更新代码

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;
    }
}

这篇关于将异步任务响应转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆