如何使用RestSharp中的ExecuteAsync返回变量

5

我在使用异步方法返回变量时遇到了问题。虽然代码可以执行,但无法返回电子邮件地址。

    public async Task<string> GetSignInName (string id)
    {

        RestClient client = new RestClient("https://graph.windows.net/{tenant}/users");
        RestRequest request = new RestRequest($"{id}");
        request.AddParameter("api-version", "1.6");
        request.AddHeader("Authorization", $"Bearer {token}");
        //string emailAddress = await client.ExecuteAsync<rootUser>(request, callback);

        var asyncHandler = client.ExecuteAsync<rootUser>(request, response =>
        {
            CallBack(response.Data.SignInNames);
        });

        return "test"; //should be a variable
    }
1个回答

5

RestSharp内置了用于执行基于任务的异步模式(TAP)的方法。这是通过RestClient.ExecuteTaskAsync<T>方法调用的。它将返回一个响应,而response.Data属性将具有您的泛型参数(在您的情况下为rootUser)的反序列化版本。

public async Task<string> GetSignInName (string id)
{
    RestClient client = new RestClient("https://graph.windows.net/{tenant}/users");
    RestRequest request = new RestRequest($"{id}");
    request.AddParameter("api-version", "1.6");
    request.AddHeader("Authorization", $"Bearer {token}");        
    var response = await client.ExecuteTaskAsync<rootUser>(request);

    if (response.ErrorException != null)
    {
        const string message = "Error retrieving response from Windows Graph API.  Check inner details for more info.";
        var exception = new Exception(message, response.ErrorException);
        throw exception;
    }

    return response.Data.Username;
}

请注意,在C#中,rootUser不是一个好的类名称。我们通常的约定是使用PascalCase类名,因此应将其更改为RootUser。

Mason,谢谢你的回答。非常有帮助。 - Christopher Norris
梅森,有没有什么方法可以加快速度?看起来执行需要10分钟,而以前只需要48秒? - Christopher Norris
1
你需要对其进行分析,找出它的瓶颈所在。仅仅这个问题不应该导致它变慢。 - mason

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接