3

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?

9
  • 2
    Use .Result to get result of task Commented Jan 15, 2017 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 Commented Jan 15, 2017 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 msdn.microsoft.com/en-us/magazine/jj991977.aspx Commented Jan 15, 2017 at 13:46
  • @Chris how is the start method being called? Commented Jan 15, 2017 at 13:50
  • @Nkosi like this for now: responseBlockTxt.Text = start(); Commented Jan 15, 2017 at 13:53

4 Answers 4

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;
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

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, that was a typo on my part. Change EventArg to RoutedEventArgs. Will update answer to fix typo.
1

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

4 Comments

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

}

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.