C# RestSharp-如何处理非200响应?RestClient在执行时引发异常
我正在Windows Phone 8.1应用程序中使用RestSharp。当服务器返回代码不同于200的响应时,RestClient引发异常。说我应该得到带有正确状态代码的响应。我想获取响应的内容,因为服务器返回错误消息C# RestSharp-如何处理非200响应?RestClient在执行时引发异常,c#,.net,windows-phone-8.1,win-universal-app,restsharp,C#,.net,Windows Phone 8.1,Win Universal App,Restsharp,我正在Windows Phone 8.1应用程序中使用RestSharp。当服务器返回代码不同于200的响应时,RestClient引发异常。说我应该得到带有正确状态代码的响应。我想获取响应的内容,因为服务器返回错误消息 private async Task<T> ExecuteAsync<T>(IRestRequest request) { if (!_networkAvailableService.IsNetworkAvailable)
private async Task<T> ExecuteAsync<T>(IRestRequest request)
{
if (!_networkAvailableService.IsNetworkAvailable)
{
throw new NoInternetException();
}
request.AddHeader("Accept", "application/json");
IRestResponse<T> response;
try
{
response = await _client.Execute<T>(request); //here I get exception
}
catch (Exception ex)
{
throw new ApiException();
}
HandleApiException(response);
return response.Data;
}
private void HandleApiException(IRestResponse response)
{
if (response.StatusCode == HttpStatusCode.OK)
{
return;
}
//never reach here :(
ApiException apiException;
try
{
var apiError = _deserializer.Deserialize<ApiErrorResponse>(response);
apiException = new ApiException(apiError);
}
catch (Exception)
{
throw new ApiException();
}
throw apiException;
}
如果您在WindowsPhone8.1下工作,那么您使用的是RestSharp Portable()(可能)。 使用以下命令:
var client = new RestClient();
client.IgnoreResponseStatusCode = true;
这样,您就不会得到404的异常。
我希望这会有帮助:)没错。使用普通RestSharp不会发生这种情况。使用RestSharp Portable时,您需要如上所述配置客户端!必须对与Xamarin一起使用的PCL组件执行此操作。
var client = new RestClient();
client.IgnoreResponseStatusCode = true;