Example #1
0
        private async Task <HttpResponse <T> > SendRequest <T>(HttpSettings settings, HttpMethod method,
                                                               HttpContent content, bool parseResult)
        {
            CheckSettings(settings);

            var url     = CreateUrl(settings);
            var request = new HttpRequestMessage(method, url);

            if (content != null)
            {
                request.Content = content;
            }

            if (_configuration.IsTokenBearer)
            {
                var token = await _localStorageService.GetItemAsync <string>(_configuration.TokenName);

                var isApiUrl = request.RequestUri?.IsAbsoluteUri ?? false;

                if (!string.IsNullOrEmpty(token) && isApiUrl)
                {
                    request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
                }
            }

            try
            {
                using var response = await _httpClient.SendAsync(request);

                if (CheckActionWasUnauthorized(response))
                {
                    return(new HttpResponse <T> {
                        IsSuccess = false
                    });
                }

                if (settings.ToasterSettings.IsNeeded)
                {
                    await _helperService.AddToaster(response, settings.ToasterSettings.Caption);
                }

                if (!response.IsSuccessStatusCode)
                {
                    return(new HttpResponse <T> {
                        IsSuccess = false
                    });
                }

                try
                {
                    if (parseResult)
                    {
                        return(new HttpResponse <T>
                        {
                            IsSuccess = true, Content = await response.Content.ReadFromJsonAsync <T>()
                        });
                    }

                    return(new HttpResponse <T> {
                        IsSuccess = true
                    });
                }
                catch (Exception e)
                {
                    ConsoleSerializationError(e);
                    return(new HttpResponse <T> {
                        IsSuccess = false
                    });
                }
            }
            catch (Exception e)
            {
                ConsoleCallError(e, url);
                return(new HttpResponse <T> {
                    IsSuccess = false
                });
            }
        }