Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return value of UploadStringAsync().?

My question is correct or incorrect I don't know, but I would like to know if is it possible to return the value of UploadStringAsync() of post methods using WebClient?

    string serviceURL = REST_URI + servicePath;
    Uri URI = new Uri(serviceURL);
    System.Net.WebClient webClient = new WebClient();
    webClient.Headers["ContentType"] = "application/json";
    webClient.Headers["Accept"] = "application/json";
    webClient.UploadStringCompleted += this.sendPostCompleted;
    webClient.UploadStringAsync(URI, HTTP_POST, result);
    return ??;

If we can return the value of UploadStringAsync(URI, HTTP_POST, result); please let me know?

like image 827
faroke moahmed Avatar asked Sep 20 '26 00:09

faroke moahmed


2 Answers

You can use UploadStringCompleted event and get result in event handler. Once upload completes (failed or succeed) event is raised.

Attach

client.UploadStringCompleted 
               += new UploadStringCompletedEventHandler (UploadStringCallback2);

Use:

void UploadStringCallback2(object sender, UploadStringCompletedEventArgs e)
{
//e.Result use it
}

If you want to return result of the upload you can wait for event to be raised like here using AutoResetEvent

like image 143
Kamil Budziewski Avatar answered Sep 22 '26 13:09

Kamil Budziewski


From .NET 4.5 we can use UploadStringTaskAsync to retrieve return value directly.

string rspBody = await client.UploadStringTaskAsync(uri, "POST");

ref: MSDN

like image 45
Circle Hsiao Avatar answered Sep 22 '26 12:09

Circle Hsiao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!