Подтвердить что ты не робот

Как реализовать ExecuteAsync с помощью RestSharp на Windows Phone 7?

Я пытаюсь использовать документацию в RestSharp GitHub wiki для реализации вызовов моей службы REST API, но у меня проблема с использованием метода ExecuteAsync.

В настоящее время мой код выглядит так для класса 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;
        });
    }
}

Я знаю, что это немного отличается от того, что находится на странице GitHub, но я использую это с WP7 и считаю, что пример для С# - это использование метода ExecuteAsync.

Моя проблема заключается в том, что должна содержать команда ExecuteAsync. Я не могу использовать return response.Data, потому что меня предупреждают:

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

Есть ли у кого-нибудь представление о том, как исправить это или учебник, который может помочь?

4b9b3361

Ответ 1

Ваш код должен выглядеть примерно так:

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);
        });
    }
}

Я добавил два метода, поэтому вы можете проверить, что вы хотите (строковое содержимое из тела ответа или десериализованный класс, представленный здесь MyClass)

Ответ 2

Старый вопрос, но если вы используете С# 5, у вас может быть общий класс выполнения, создав TaskCompleteSource, который возвращает Task of T. Ваш код может выглядеть так:

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;
    }

И используйте его следующим образом:

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
    }

Ответ 3

Или, точнее, это:

    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;
    }

Ответ 4

Следующее выполнило задание

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>;

}

Ответ 5

В качестве альтернативы (или дополнения) к тонкому ответу 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;
}