Windows Phone 8上的RestSharp没有响应

时间:2014-09-09 20:47:00

标签: c# rest windows-phone-8 restsharp

我尝试使用RestSharp连接到我的API。当我尝试使用该代码时:

var client = new RestClient("http://api.com");
var request = new RestRequest("api/login", Method.POST);
client.Authenticator = new HttpBasicAuthenticator("login", "pass");
request.AddHeader("Accept", "*/*");
request.RequestFormat = DataFormat.Json;
 request.AddBody(new { customer = new { email = "email", password = "pass" } });
var response = client.Execute(request);
Console.WriteLine(response.Content);
Console.ReadKey();

我从服务器得到了正确的回复

但是当谈到Windows Phone 8时

var client = new RestClient("http://api.com"); ;
client.Authenticator = new HttpBasicAuthenticator("login", "pass");
var request = new RestRequest("api/login", Method.POST);
request.AddHeader("Accept", "*/*");

request.RequestFormat = DataFormat.Json;
request.AddBody(new { customer = new { email = "email", password = "pass" } });

 client.ExecuteAsync(request, response =>
{
    lblStatus.Text = response.Content ;
});

我找不到状态码,服务器为null。我做错了什么?

2 个答案:

答案 0 :(得分:3)

我认为,您必须同步发送请求。只需创建类,如下所示:

public static class RestClientExtensions
{
    public static Task<IRestResponse> ExecuteTask(this IRestClient client, RestRequest request)
    {
        var TaskCompletionSource = new TaskCompletionSource<IRestResponse>();
        client.ExecuteAsync(request, (response, asyncHandle) =>
        {
            if (response.ResponseStatus == ResponseStatus.Error)
                TaskCompletionSource.SetException(response.ErrorException);
            else
                TaskCompletionSource.SetResult(response);
        });
        return TaskCompletionSource.Task;
    }
}

现在,您可以像这样使用它:

IRestResponse restResponse = await app.Client.ExecuteTask(request);

在此行之后,您可以轻松获得响应内容,就像您之前所做的那样:

lblStatus.Text = response.Content ;

我希望它会对你有所帮助。

答案 1 :(得分:1)

代码

var client = new RestClient(basicUrl);
client.ExecuteAsync<User>(request, (response) =>
        {
            user = response.Data;
        });
txtBox.Text = user.Name; //<---- its outside the Async event handler 
                        //so at this point user doesn't     
                        //have the info of the response

您需要将该行更改为异步响应方法