public async Task <TResult> GetAsyncEx <TResult>(string url) where TResult : IErrorResult, new() { await _loaderService.LoadStart(); var token = await _localStorageService.GetItemAsync <string>(Const.Token); if (!String.IsNullOrWhiteSpace(token)) { this.DefaultRequestHeaders.Remove(Const.Token); this.DefaultRequestHeaders.Add(Const.Token, token); } var result = await this.GetFromJsonAsync <TResult>(url); await _loaderService.LoadEnd(); if (!result.HasError) { return(result); } OnApiError?.Invoke(this, result); return(result); }
public async Task <TResult> PutAsyncEx <TResult, TValue>(string url, TValue model, string actionName) where TResult : IErrorResult, new() { await _loaderService.LoadStart(); var token = await _localStorageService.GetItemAsync <string>(Const.Token); if (!String.IsNullOrWhiteSpace(token)) { this.DefaultRequestHeaders.Remove(Const.Token); this.DefaultRequestHeaders.Add(Const.Token, token); } if (!String.IsNullOrWhiteSpace(actionName)) { this.DefaultRequestHeaders.Remove(Const.ActionTitle); this.DefaultRequestHeaders.Add(Const.ActionTitle, actionName); } var response = await this.PutAsJsonAsync <TValue>(url, model); await _loaderService.LoadEnd(); if (!response.IsSuccessStatusCode) { var errorResult = new TResult() { ErrorMessage = response.StatusCode.ToString() }; OnApiError?.Invoke(this, errorResult); return(errorResult); } var result = await response.Content.ReadFromJsonAsync <TResult>(); if (!result.HasError) { return(result); } OnApiError?.Invoke(this, result); return(result); }
private T SendApiRequest <T>(string content, string apiMethod, Func <string, T> parser) where T : class { var request = new HttpRequestMessage(HttpMethod.Post, $"{_host}/{apiMethod}"); request.Content = new StringContent(content, Encoding.UTF8, "application/x-www-form-urlencoded"); HttpResponseMessage response; try { response = _http.SendAsync(request).Result; } catch (Exception e) { LogOut(); OnApiError?.Invoke(e.Message); return(null); } var responseBody = response.Content.ReadAsStringAsync().Result; if (response.StatusCode != HttpStatusCode.OK) { OnApiError?.Invoke(responseBody); return(null); } try { var data = parser(responseBody); return(data); } catch (Exception ex) { OnApiError?.Invoke(ex.Message); return(null); } }