Return 来自网络的字符串 API DownloadCompleteAsync

Return string from Web API DownloadCompleteAsync

我正在开发一个 Windows Phone 应用程序,但我卡在了某个部分。 我的项目在 c#/xaml - VS2013.

问题: 我有一个列表选择器(名称 - UserPicker),它是所有用户名的列表。现在我想从数据库中获取该用户名的用户 ID。我已经实现了 Web Api 并且我正在使用 Json 进行反序列化。 但是我无法 return 来自 DownloadCompleted 事件的字符串。

代码:

string usid = "";
        
        selecteduser = (string)UserPicker.SelectedItem;
        string uri = "http://localhost:1361/api/user";
        WebClient client = new WebClient();
        client.Headers["Accept"] = "application/json";
        client.DownloadStringAsync(new Uri(uri));
        //client.DownloadStringCompleted += client_DownloadStringCompleted;
        client.DownloadStringCompleted += (s1, e1) =>
        {
            //var data = JsonConvert.DeserializeObject<Chore[]>(e1.Result.ToString());
            //MessageBox.Show(data.ToString());
            var user = JsonConvert.DeserializeObject<User[]>(e1.Result.ToString());
            foreach (User u in user)
            {
                if (u.UName == selecteduser)
                {
                    usid = u.UserID;
                    
                }
                //result.Add(c);

                return usid;
            }
            //return usid
        };

我想 return 所选用户的用户 ID。但它给我以下错误。

Since 'System.Net.DownloadStringCompletedEventHandler' returns void, a return keyword must not be followed by an object expression

Cannot convert lambda expression to delegate type 'System.Net.DownloadStringCompletedEventHandler' because some of the return types in the block are not implicitly convertible to the delegate return type

如果你查看 DownloadStringCompletedEventHandler 的源代码,你会发现它是这样实现的:

public delegate void DownloadStringCompletedEventHandler(
   object sender, DownloadStringCompletedEventArgs e);

这意味着您无法 return 从中获取任何数据。您可能有一些方法可以对选定的用户 ID 执行某些操作。您需要从事件处理程序中调用此方法。因此,如果此方法被命名为 HandleSelectedUserId,那么代码可能如下所示:

client.DownloadStringCompleted += (sender, e) =>
{
    string selectedUserId = null;
    var users = JsonConvert.DeserializeObject<User[]>(e.Result.ToString());
    foreach (User user in users)
    {
        if (user.UName == selecteduser)
        {
            selectedUserId = user.UserID;
            break;
        }
    }

    HandleSelectedUserId(selectedUserId);
};
client.DownloadStringAsync(new Uri("http://some.url"));

在调用 DownloadStringAsync 方法之前为 DownloadStringCompleted 事件添加事件处理程序也是一个好主意。