I am performing an HttpRequest. It turns out that when I return the response and show it to work on it, it shows me this:
System.Threading.Tasks.Task`1[System.String]
My code is:
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace MLWPF.HttpRequest
{
class Client
{
private static readonly HttpClient httpClient = new HttpClient();
private FormUrlEncodedContent content;
public int Id { get; set; }
public int Uid { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public double Phone { get; set; }
public Client()
{
}
public Client(int id, int uid, string name, string address, double phone)
{
Id = id;
Uid = uid;
Name = name;
Address = address;
Phone = phone;
}
public async Task<string> ReadClients(int uid)
{
var values = new Dictionary<string, string>()
{
{"uid", uid.ToString()}
};
content = new FormUrlEncodedContent(values);
HttpResponseMessage response = await httpClient.PostAsync(new UrlHttpRequest().UrlReadClients, content);
string responseString = await response.Content.ReadAsStringAsync();
return responseString;
}
}
}
It turns out that if I show in the console before returning the responseString
, the information obtained is displayed correctly.
I am calling it from a method in the MainWindow.xaml.cs connected to a button.
private void FAB_Tab1_Button_Click(object sender, RoutedEventArgs e)
{
Client client = new Client();
client.ReadClients(1);
Console.WriteLine(client.Name);
}
How can I do so that when I return I get the information I need?
One option is to use the method
Task.FromResult<TResult>
, where you would only changereturn responseString;
toreturn Task.FromResult<responseString>;
, leaving your code as follows:Or in your case, change the line from
HttpResponseMessag response = ...
toHttpResponseMessage response = await Task.FromResult<string>(httpClient.PostAsync(new UrlHttpRequest().UrlReadClients, content));
OP comments:
Indeed, that is the problem. Since
ReadClients
it's a methodasync
, to get the return value, you need to useawait
:However, if you are making the call from
main
for example, which you cannot mark asasync
, then you would have to make the call like this:But it should be noted that as of C# 7.1 it is possible to mark the
main
withasync
in the following way:Edit based on the code you added to your question
If you are trying to make the call from an event handler, you must add
async
to the event handler's signature and runReadClients
withawait
:...or, if you fall back to your original version of
ReadClients
which directly returns the desired result (probably a good idea), it's basically the same:I found another way to get the information. To make it easier I created a new string variable inside the class to which I assign the
public string s = responseString;
so when I instantiate it I do it in a new way.This way I get the content that returns.