【问题标题】:How to Use ExecuteAsync in RestSharp to return variable如何在 RestSharp 中使用 ExecuteAsync 返回变量
【发布时间】:2019-02-08 05:39:14
【问题描述】:

我在异步方法中返回变量时遇到问题。我能够让代码执行,但我无法让代码返回电子邮件地址。

    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
    }

【问题讨论】:

    标签: c# .net asynchronous restsharp


    【解决方案1】:

    RestSharp 内置了用于执行基于任务的异步模式 (TAP) 的方法。这是通过RestClient.ExecuteTaskAsync&lt;T&gt; 方法调用的。这会给您一个响应,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;
    }
    

    请注意,rootUser 不是 C# 中类的好名称。我们通常的约定是 PascalCase 类名,所以它应该是 RootUser。

    【讨论】:

    • 梅森,谢谢你的回答。很有帮助。
    • 梅森,有没有办法加快速度?以前需要 48 秒,现在好像需要 10 分钟来执行?
    • 您必须对其进行分析并确定减速的原因。仅此一项就不应该让它变慢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多