2

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

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

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.

When I use the following code:

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

}

The output is:

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

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

Nkosi
  • 235,767
  • 35
  • 427
  • 472
Chris
  • 1,574
  • 4
  • 16
  • 49
  • 2
    Use .Result to get result of task – Maksim Simkin Jan 15 '17 at 13:38
  • @MaksimSimkin results in the following error: `An exception of type 'System.AggregateException' occurred in mscorlib.ni.dll but was not handled in user code` – Chris Jan 15 '17 at 13:39
  • 1
    @Chris Don't mix async and blocking calls (`.Result, .Wait()`) you may get deadlocks. Go async all the way. Read up here https://msdn.microsoft.com/en-us/magazine/jj991977.aspx – Nkosi Jan 15 '17 at 13:46
  • @Chris how is the start method being called? – Nkosi Jan 15 '17 at 13:50
  • @Nkosi like this for now: `responseBlockTxt.Text = start();` – Chris Jan 15 '17 at 13:53
  • Is that line of code being done in an event handler? If yes there is a really easy fix. – Nkosi Jan 15 '17 at 13:55
  • @Nkosi I updated the post with some more code – Chris Jan 15 '17 at 13:55
  • @Chris this is a classic XY problem. in future when explaining a problem provide a [mcve] that reproduces the issue so that those trying to help you have the complete picture and would be able to provide better answers. It reduces the back and forth trying to figure out what is really the problem when the information provided is vague. – Nkosi Jan 15 '17 at 14:05
  • What is the nameplace for "Windows.UI" on WinForms? – qtg Apr 29 '21 at 01:45

4 Answers4

4

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

Read up on Async/Await - Best Practices in Asynchronous Programming

And then update your code accordingly

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;
    }
}
Nkosi
  • 235,767
  • 35
  • 427
  • 472
  • Alright, we're going in the right direction. The only error that pops-up now is at `this.Loaded += OnLoad;`. Error: `No overload for 'OnLoad' matches delegate 'RoutedEventHandler'` – Chris Jan 15 '17 at 16:02
  • 1
    @Chris, that was a typo on my part. Change `EventArg` to `RoutedEventArgs`. Will update answer to fix typo. – Nkosi Jan 15 '17 at 16:06
1

I Guess

public string start()
{
    var response = sendRequest();
    Task<String> t = sendRequest();
    System.Diagnostics.Debug.WriteLine(t.Result);

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

}
Stilet
  • 92
  • 2
0

The problem is in the start method, the SendRequest method returns a Task<string> and that's what you get on your response variable. Since you are attempting to run an async method synchronously you have to do some extra stuff, try this:

public string start()
{
    var response = sendRequest().ConfigureAwait(true)
                                .GetAwaiter()
                                .GetResult();

    System.Diagnostics.Debug.WriteLine(response);

    return "";
}

That get the actual result inside your awaitable Task<string>. If you want to find some more info on this take a look at this question

Community
  • 1
  • 1
Luiso
  • 4,173
  • 2
  • 37
  • 60
  • Hey @Luiso. Thanks for the answer. Unfortunately, the following error pops-up now: `An exception of type 'System.Net.Http.HttpRequestException' occurred in mscorlib.ni.dll but was not handled in user code` – Chris Jan 15 '17 at 13:44
  • That means there is something wrong with your request, you had an issue with concurrency now you have one with the request, please update your question and add as much data as you can so we can improve on that – Luiso Jan 15 '17 at 13:47
  • What I'm showing is pretty much all I have. The url I'm using is working just fine. I'm used to use it in AJAX. Now trying to use the same thing in here. – Chris Jan 15 '17 at 13:50
  • I think you should take a look at what the actual `Exception` looks like. With what you're giving us we can only tell there is something wrong with the request, and not _what_ went wrong with it – Luiso Jan 15 '17 at 14:04
0
public string start()
  {
    var response = sendRequest().ConfigureAwait(true)
                                .GetAwaiter()
                                .GetResult();

    System.Diagnostics.Debug.WriteLine(response);
    return "";
   }

I have Tried this. It is working perfectly.

Kamal Panhwar
  • 2,345
  • 3
  • 21
  • 37