我尝试使用 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 ;
});
我没有找到状态代码,服务器为空。我做错了什么?
最佳答案
我认为,您必须同步发送请求。只需创建类,如下所示:
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 ;
希望对您有所帮助。
关于c# - Windows Phone 8 上的 RestSharp 没有响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25753304/