// Returns the JavaScript version of the Web API error code, as contained in the specified WebApiException // object, or null if not present. This will be either a WebApiErrorCode enum identifier in string form (e.g. // "StartDateFormatInvalid"), or an integer in string form (if we don't recognise the error code). public static String GetJsWebApiErrorCode(WebApiException ex) { if (ex == null) return (null); if (ex.ErrorCode != null) return ex.ErrorCode.Value.ToString(); if (ex.UnrecognisedErrorCode != null) return ex.UnrecognisedErrorCode.Value.ToString(CultureInfo.InvariantCulture); return null; }
public async Task <TResultData> PostAsync <TData, TResultData>(string relativeUrl, TData postData, bool isAnonymousRequest = false) { TResultData result = default(TResultData); try { if (!isAnonymousRequest) { await AutoConnectAsync(); } string postBody = JsonConvert.SerializeObject(postData, new JsonSerializerSettings { Formatting = Formatting.None }); var httpResponse = await _httpClient.PostAsync(relativeUrl, new StringContent(postBody, Encoding.UTF8, "application/json")); if (httpResponse != null) { if (httpResponse.StatusCode == HttpStatusCode.OK) { if (httpResponse.Content.Headers != null && httpResponse.Content.Headers.ContentType != null && httpResponse.Content.Headers.ContentType.MediaType == "application/pdf" && typeof(TResultData) == typeof(MemoryStream)) { result = (TResultData)Activator.CreateInstance(typeof(TResultData)); var memoryStream = result as MemoryStream; using (Stream streamToReadFrom = await httpResponse.Content.ReadAsStreamAsync()) { await streamToReadFrom.CopyToAsync(memoryStream); httpResponse.Content = null; } } else { var jsonStringResult = httpResponse.Content.ReadAsStringAsync().Result; if (!string.IsNullOrEmpty(jsonStringResult)) { result = JsonConvert.DeserializeObject <TResultData>(jsonStringResult); } } } else if (httpResponse.StatusCode == HttpStatusCode.NoContent) { result = default(TResultData); } else if (httpResponse.StatusCode == HttpStatusCode.NotFound) { throw new HttpException((int)httpResponse.StatusCode, "Ressource not found"); } else if (httpResponse.StatusCode == HttpStatusCode.Forbidden) { _connected = false; throw new HttpException((int)httpResponse.StatusCode, "Ressource forbidden"); } else if (httpResponse.StatusCode == HttpStatusCode.BadRequest) { var jsonStringResult = httpResponse.Content.ReadAsStringAsync().Result; WebApiException webApiException = ConvertJsonExceptionToWebApiException(jsonStringResult); if (webApiException != null) { throw webApiException; } throw new HttpException((int)httpResponse.StatusCode, "Bad request"); } else { throw new HttpException((int)httpResponse.StatusCode, "error"); } } } catch (TaskCanceledException timeoutException) { throw new HttpException(Translation.Get(TRS.TIMEOUT), timeoutException); } catch (Exception exception) { if (exception is HttpException || exception is WebApiException) { throw exception; } throw new HttpException(Translation.Get(TRS.UNABLE_TO_CONNECT_TO_SERVER_P_PLEASE_RETRY_P), exception); } return(result); }
// Returns an appropriate WebApiResourceResult according to the error condition in getting a Web API resource, // indicated by the specified WebApiException (which must not be null). 'attempt' specifies the number of // attempt to get the resource (0 = first attempt; 1 = second attempt). If the error condition is that // the access token has expired, the method MAY return null and pass back 'getNewAccessToken' as true; in // this case the calling code should get a new access token from the user's refresh token, and then re-try // to get the same resource. public static JsonResult<WebApiResourceResult> GetWebApiResourceResultOnError(WebApiException ex, Int32 attempt, out Boolean getNewAccessToken) { // Default. getNewAccessToken = false; // Sanity check. if (ex == null) return null; // If there's no HTTP status code, then we suffered an unexpected, technical error and we // weren't able to talk to the Web API (or any HTTP intermediary). if (ex.StatusCode == null) { return ToJsonResult(new WebApiResourceResult() { success = false, failedMessage = ex.Message }); } // If the access token has expired or is invalid... if (ex.AccessTokenExpiredOrInvalid) { // For attempt #1... if (attempt == 0) { // We'll assume that the access token has expired. It's unlikely that the OAuth2 Server // has given us an invalid one, and it's unlikely that we've presented the access token // incorrectly. So we'll return saying that the OAuth2 Server should be asked for a new // access token via the user's refresh token. getNewAccessToken = true; return null; } // For subsequent attempts... else { return ToJsonResult(new WebApiResourceResult() { httpStatus = (Int32)ex.StatusCode.Value, reasonPhrase = "Access to the Web API has been denied.", }); } } // If we wanted, we could do something server-side if the request has been forbidden due to a // Fair Usage Policy violation, such as log the user out. For now we'll let the JavaScript // handle it. // if (ex.RequestForbiddenDueToFairUsagePolicyViolation) // { // // do something // } // For all other error conditions... return ToJsonResult(new WebApiResourceResult() { httpStatus = (Int32)ex.StatusCode.Value, reasonPhrase = ex.Message, webApiErrorCode = GetJsWebApiErrorCode(ex) }); }
public async Task <T> GetAsync <T>(string relativeUrl, Dictionary <string, string> datas = null) { T result = default(T); try { await AutoConnectAsync(); HttpResponseMessage httpResponse; if (datas != null && datas.Count > 0) { var postData = new List <KeyValuePair <string, string> >(); postData.AddRange(datas); HttpContent content = new FormUrlEncodedContent(postData); string urlDatas = await content.ReadAsStringAsync(); httpResponse = await _httpClient.GetAsync(string.Format("{0}?{1}", relativeUrl, urlDatas)); } else { httpResponse = await _httpClient.GetAsync(relativeUrl); } if (httpResponse != null) { if (httpResponse.StatusCode == HttpStatusCode.OK) { var jsonStringResult = httpResponse.Content.ReadAsStringAsync().Result; if (!string.IsNullOrEmpty(jsonStringResult)) { result = JsonConvert.DeserializeObject <T>(jsonStringResult); } } else if (httpResponse.StatusCode == HttpStatusCode.NoContent) { result = default(T); } else if (httpResponse.StatusCode == HttpStatusCode.NotFound) { throw new HttpException((int)httpResponse.StatusCode, "Ressource not found"); } else if (httpResponse.StatusCode == HttpStatusCode.Forbidden) { _connected = false; throw new HttpException((int)httpResponse.StatusCode, "Ressource forbidden"); } else if (httpResponse.StatusCode == HttpStatusCode.BadRequest) { var jsonStringResult = httpResponse.Content.ReadAsStringAsync().Result; WebApiException webApiException = ConvertJsonExceptionToWebApiException(jsonStringResult); if (webApiException != null) { throw webApiException; } throw new HttpException("Bad HTTP request"); } else { throw new HttpException((int)httpResponse.StatusCode, "error"); } } } catch (TaskCanceledException timeoutException) { throw new HttpException(Translation.Get(TRS.TIMEOUT), timeoutException); } catch (Exception exception) { if (exception is HttpException || exception is WebApiException) { throw exception; } throw new HttpException(Translation.Get(TRS.UNABLE_TO_CONNECT_TO_SERVER_P_PLEASE_RETRY_P), exception); } return(result); }