Return value of UploadStringAsync().?

萝らか妹 提交于 2019-12-02 03:01:38

问题


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?


回答1:


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




回答2:


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

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

ref: MSDN




回答3:


There is nothing to return from that function. You've already set up an event handler for UploadStringCompleted, you can get the result of the action in the handler.

This is the signature:

public delegate void UploadStringCompletedEventHandler(
    Object sender,
    UploadStringCompletedEventArgs e
)

The second parameter has the information you need: UploadStringCompletedEventArgs, the Result property contains the server's response.



来源:https://stackoverflow.com/questions/20374582/return-value-of-uploadstringasync

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!