C# 我应该如何在 Windows Phone 7 上使用 RestSharp 实现 ExecuteAsync?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10153749/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 12:40:41  来源:igfitidea点击:

How should I implement ExecuteAsync with RestSharp on Windows Phone 7?

c#apiwindows-phone-7restrestsharp

提问by joshcollie

I'm attempting to use the documentation on the RestSharp GitHub wikito implement calls to my REST API service but I'm having an issue with the ExecuteAsync method in particular.

我正在尝试使用RestSharp GitHub wiki上的文档来实现对我的 REST API 服务的调用,但我遇到了特别是 ExecuteAsync 方法的问题。

Currently my code looks like this for the API class:

目前,我的 API 类代码如下所示:

public class HarooApi
{
    const string BaseUrl = "https://domain.here";

    readonly string _accountSid;
    readonly string _secretKey;

    public HarooApi(string accountSid, string secretKey)
    {
        _accountSid = accountSid;
        _secretKey = secretKey;
    }

    public T Execute<T>(RestRequest request) where T : new()
    {
        var client = new RestClient();
        client.BaseUrl = BaseUrl;
        client.Authenticator = new HttpBasicAuthenticator(_accountSid, _secretKey);
        request.AddParameter("AccountSid", _accountSid, ParameterType.UrlSegment);
        client.ExecuteAsync<T>(request, (response) =>
        {
            return response.Data;
        });
    }
}

I'm aware this slightly deviates from what is on the GitHub page but I'm using this with WP7 and believe the example is for C# hence the usage of the ExecuteAsync method.

我知道这与 GitHub 页面上的内容略有不同,但我将它与 WP7 一起使用,并相信该示例适用于 C#,因此使用了 ExecuteAsync 方法。

My problem is with what the ExecuteAsync command should contain. I can't use return response.Databecause I'm warned:

我的问题是 ExecuteAsync 命令应该包含什么。我不能使用,return response.Data因为我被警告:

'System.Action<RestSharp.RestResponse<T>,RestSharp.RestRequestAsyncHandle>' returns void, a return keyword must not be followed by an object expression

Does anyone have any insight on how to fix this or a tutorial that may assist?

有没有人对如何解决这个问题或可能有帮助的教程有任何见解?

采纳答案by Pedro Lamas

Your code should look something like this:

您的代码应如下所示:

public class HarooApi
{
    const string BaseUrl = "https://domain.here";

    readonly string _accountSid;
    readonly string _secretKey;

    public HarooApi(string accountSid, string secretKey)
    {
        _accountSid = accountSid;
        _secretKey = secretKey;
    }

    public void ExecuteAndGetContent(RestRequest request, Action<string> callback)
    {
        var client = new RestClient();
        client.BaseUrl = BaseUrl;
        client.Authenticator = new HttpBasicAuthenticator(_accountSid, _secretKey);
        request.AddParameter("AccountSid", _accountSid, ParameterType.UrlSegment);
        client.ExecuteAsync(request, response =>
        {
            callback(response.Content);
        });
    }

    public void ExecuteAndGetMyClass(RestRequest request, Action<MyClass> callback)
    {
        var client = new RestClient();
        client.BaseUrl = BaseUrl;
        client.Authenticator = new HttpBasicAuthenticator(_accountSid, _secretKey);
        request.AddParameter("AccountSid", _accountSid, ParameterType.UrlSegment);
        client.ExecuteAsync<MyClass>(request, (response) =>
        {
            callback(response.Data);
        });
    }
}

I added two methods, so you can check what you want (string content from the response body, or a deserialized class represented here by MyClass)

我添加了两个方法,因此您可以检查您想要的内容(来自响应正文的字符串内容,或此处由 表示的反序列化类MyClass

回答by Gusten

Old question but if you are using C# 5 you can have a generic execute class by creating a TaskCompleteSource that resturns a Task of T. Your code could look like this:

老问题,但如果您使用的是 C# 5,您可以通过创建一个返回 T 任务的 TaskCompleteSource 来拥有一个通用的执行类。您的代码可能如下所示:

public Task<T> ExecuteAsync<T>(RestRequest request) where T : new()
    {
        var client = new RestClient();
        var taskCompletionSource = new TaskCompletionSource<T>();
        client.BaseUrl = BaseUrl;
        client.Authenticator = new HttpBasicAuthenticator(_accountSid, _secretKey);
        request.AddParameter("AccountSid", _accountSid, ParameterType.UrlSegment);
        client.ExecuteAsync<T>(request, (response) => taskCompletionSource.SetResult(response.Data));
        return taskCompletionSource.Task;
    }

And use it like this:

并像这样使用它:

private async Task DoWork()
    {
        var api = new HarooApi("MyAcoountId", "MySecret");
        var request = new RestRequest();
        var myClass = await api.ExecuteAsync<MyClass>(request);

        // Do something with myClass
    }

回答by ageroh

The following did the job

以下做了这项工作

public async Task<IRestResponse<T>> ExecuteAsync<T>(IRestRequest request) where T : class, new()
{
    var client = new RestClient
    {
        BaseUrl = _baseUrl,
        Authenticator = new HttpBasicAuthenticator(_useraname, _password),
        Timeout = 3000,
    };

    var tcs = new TaskCompletionSource<T>();
    client.ExecuteAsync<T>(request, restResponse =>
    {
        if (restResponse.ErrorException != null)
        {
            const string message = "Error retrieving response.";
            throw new ApplicationException(message, restResponse.ErrorException);
        }
        tcs.SetResult(restResponse.Data);
    });

    return await tcs.Task as IRestResponse<T>;

}

回答by Per Schondell

Or more precisely like this:

或者更准确地说是这样的:

    public async Task<IRestResponse<T>> ExecuteAsync<T>(IRestRequest request) where T : class, new()
    {
        var client = new RestClient(_settingsViewModel.BaseUrl);

        var taskCompletionSource = new TaskCompletionSource<IRestResponse<T>>();
        client.ExecuteAsync<T>(request, restResponse =>
        {
            if (restResponse.ErrorException != null)
            {
                const string message = "Error retrieving response.";
                throw new ApplicationException(message, restResponse.ErrorException);
            }
            taskCompletionSource.SetResult(restResponse);
        });

        return await taskCompletionSource.Task;
    }

回答by smoksnes

As an alternative (or complement) to the fine answerby Gusten. You can use ExecuteTaskAsync. This way you do not manually have to handle TaskCompletionSource. Note the asynckeyword in the signature.

作为替代(或补充)的罚款答案通过Gusten。您可以使用ExecuteTaskAsync. 这样你就不用手动去处理了TaskCompletionSource。注意async签名中的关键字。

public async Task<T> ExecuteAsync<T>(RestRequest request) where T : new()
{
    var client = new RestClient();
    client.BaseUrl = BaseUrl;
    client.Authenticator = new HttpBasicAuthenticator(_accountSid, _secretKey);
    request.AddParameter("AccountSid", _accountSid, ParameterType.UrlSegment);
    IRestResponse<T> response = await client.ExecuteTaskAsync<T>(request);
    return response.Data;
}