c# – RestSharp – 如何处理非200响应? RestClient在Execute上
发布时间:2020-12-15 23:27:37 所属栏目:百科 来源:网络整理
导读:我在 Windows Phone 8.1应用程序中使用RestSharp.当服务器返回代码不同于200的响应时,RestClient抛出异常. Wiki表示我应该使用正确的状态代码获得响应.我想得到响应的内容,因为服务器返回错误消息. private async TaskT ExecuteAsyncT(IRestRequest request)
我在
Windows Phone 8.1应用程序中使用RestSharp.当服务器返回代码不同于200的响应时,RestClient抛出异常.
Wiki表示我应该使用正确的状态代码获得响应.我想得到响应的内容,因为服务器返回错误消息.
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; } 服务器响应示例: HTTP/1.1 400 Bad Request Cache-Control: no-cache Pragma: no-cache Content-Length: 86 Content-Type: application/json;charset=UTF-8 Expires: -1 Server: Microsoft-IIS/8.0 Access-Control-Allow-Origin: * X-Powered-By: ASP.NET Date: Mon,28 Sep 2015 12:30:10 GMT Connection: close {"error":"invalid_token","error_description":"The user name or password is incorrect"} 解决方法
如果您在Windows Phone 8.1下工作,则使用的是RestSharp Portable(
https://github.com/FubarDevelopment/restsharp.portable)(可能).
用这个: var client = new RestClient(); client.IgnoreResponseStatusCode = true; 有了这个,例如,你不会因404而异常.我希望它会有所帮助:) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |