引发UploadStringCompleted事件后的返回值?

时间:2014-11-11 10:13:16

标签: c# asp.net-mvc return webclient

我能够从客户端上传数据,并获得响应。我的问题是如何在UploadStringCompleted事件完成后从LoginRequest方法返回一个值。 或者如何从UploadStringCompleted事件返回值。请参阅下面的代码。 但是当我执行返回“true”行时,在调用webClientLogin_UploadStringCompleted方法之前执行。 下面的链接有类似的东西,但我没有得到我的问题的答案 点击[这里](Return value of UploadStringAsync().?) 在此先感谢。

public string LoginRequest(string token)
{
    WebClient client = new WebClient();
    JavaScriptSerializer serializer = new JavaScriptSerializer();
    var result= serializer.Serialize(token);
    client .Headers["ContentType"] = "application/json";
    client.UploadStringCompleted += new UploadStringCompletedEventHandler(webClientLogin_UploadStringCompleted);
    client.UploadStringAsync(URI, HTTP_POST, result);
    return "true";
}

private void webClientLogin_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
    var validate = JsonConvert.DeserializeObject<string>(e.Result);  
}

我应该对AutoResetEvent或ManualReSetEvent做什么吗?

2 个答案:

答案 0 :(得分:1)

您不应该从LoginRequest方法返回任何内容。而是从webClientLogin_UploadStringCompleted事件中执行您想要执行的操作。因为上传完成后会调用它。

答案 1 :(得分:0)

您可以使用UploadStringTaskAsync返回Task<string>,以便您使用async / await。试试这个:

public async Task<string> LoginRequest(string token)
{
    JavaScriptSerializer serializer = new JavaScriptSerializer();
    var result = serializer.Serialize(token);

    WebClient client = new WebClient();
    client.Headers["ContentType"] = "application/json";
    var response = await client.UploadStringTaskAsync(URI, HTTP_POST, result);
    // do something with the response here, eg. JsonConvert.DeserializeObject();

    return "true";
}

另外,为什么要将true作为字符串返回?如果可以,请使用布尔值。