private IFlurlRequest CreateRequest() { var flurlRequest = new FlurlRequest(url) { Client = flurlClientFactory.Get(url) }; flurlRequest.WithHeader(CorrelationContext.CorrelationIdName, CorrelationContext.CorrelationId.Value); if (headers != null) { foreach (var header in headers) { flurlRequest.WithHeader(header.Key, header.Value); } } flurlRequest.Settings = defaultFlurlHttpSettings.Create(); flurlRequest.WithTimeout(timeout); return(flurlRequest); }
public async Task <IRwsResponse> SendRequestAsync(IRwsRequest request, int?timeout = null) { var client = new FlurlRequest(Url.Combine(BaseUrl, request.UrlPath())); if (timeout != null) { client.WithTimeout((int)timeout); } if (request.RequiresAuthentication) { client.WithBasicAuth(_username, _password); } client.WithHeaders(request.Headers); var stopwatch = Stopwatch.StartNew(); HttpResponseMessage response = null; try { response = await client.AllowAnyHttpStatus().SendAsync(request.Method, request.RequestBody); } catch (FlurlHttpTimeoutException ex) { throw new RwsException($"Connection timeout for {client.Url.ToString()}", ex); } stopwatch.Stop(); LastResult = response; RequestTime = stopwatch.Elapsed; RwsExceptionHandler.Parse(response); return(request.Result(response)); }
private async Task <T> ProcessGetAsync <T>(string url, Dictionary <string, string> headers = null, object requestParams = null, string accessToken = "", int timeout = 10, bool isThrowException = true) { var result = new RestApiResponse <T>(); try { var _request = new Url(url); var _flurlRequest = new FlurlRequest(_request); if (!string.IsNullOrEmpty(accessToken)) { _flurlRequest = _flurlRequest.WithHeader("Authorization", accessToken); } if (headers != null && headers.Count > 0) { foreach (var item in headers) { _flurlRequest = _flurlRequest.WithHeader(item.Key, item.Value); } } var response = requestParams != null ? await _flurlRequest.SetQueryParams(requestParams).WithTimeout(timeout).GetAsync() : await _flurlRequest.WithTimeout(timeout).GetAsync(); if (response.IsSuccessStatusCode) { var stringResponse = await response.Content.ReadAsStringAsync(); result.Result = JsonConvert.DeserializeObject <T>(stringResponse); result.IsSuccess = true; } } catch (FlurlHttpTimeoutException timeoutex) { result.IsSuccess = false; result.ExceptionMessage = "Time out"; result.Exception = timeoutex; } catch (FlurlHttpException ex) { var errorResponse = await ex.GetResponseStringAsync(); result.Exception = ex; result.ExceptionMessage = ex.Message; result.IsSuccess = false; //Try parse response to Custom Exception try { var customException = JsonConvert.DeserializeObject <CustomExceptionResponse>(errorResponse); if (customException != null) { result.IsCustomException = true; result.CustomException = customException; result.IsSuccess = false; } } catch { // KhuongDang : No content } } catch (Exception ex) { result.IsSuccess = false; result.Exception = ex; } WriteLog(url, result, requestParams, isThrowException); return(result.Result); }