Created
June 21, 2019 09:24
-
-
Save XEngine/bfc2bf0e78ac8baf4ad28e05ecf024d9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Diagnostics; | |
using System.Linq; | |
using System.Net.Http; | |
using System.Net.Http.Headers; | |
using System.Threading.Tasks; | |
using Microsoft.AspNetCore.Http; | |
using Newtonsoft.Json; | |
using Shared.Services; | |
using System.Text; | |
using Shared.Extensions; | |
using Shared.Models; | |
namespace Shared.Utilities | |
{ | |
public class Client : IDisposable | |
{ | |
private readonly HttpClient _client = new HttpClient | |
{ | |
BaseAddress = new Uri(Environment.GetEnvironmentVariable("APIURL") ?? "http://127.0.0.1:8080/api/v2/"), | |
Timeout = TimeSpan.FromSeconds(20) | |
}; | |
public Client(Uri baseAddress) | |
{ | |
if (!baseAddress.IsWellFormedOriginalString() && !string.IsNullOrWhiteSpace(baseAddress.ToString())) | |
{ | |
throw new Exception("Base address must set while creating a Client instance"); | |
} | |
_client.BaseAddress = baseAddress; | |
_client.DefaultRequestHeaders | |
.Accept | |
.Add(new MediaTypeWithQualityHeaderValue("application/json")); | |
} | |
public Task<T> GetAsync<T>(string endpoint, object request = null) | |
{ | |
var req = request != null ? "?" + request.GetQueryString() : ""; | |
return Invoke( | |
client => client.GetAsync($"{endpoint}{req}"), | |
async message => JsonConvert.DeserializeObject<T>(await message.Content.ReadAsStringAsync()) | |
); | |
} | |
public Task<T> DeleteAsync<T>(string endpoint, object request = null) | |
{ | |
var req = request != null ? "?" + request.GetQueryString() : ""; | |
return Invoke( | |
client => client.DeleteAsync($"{endpoint}{req}"), | |
async message => JsonConvert.DeserializeObject<T>(await message.Content.ReadAsStringAsync()) | |
); | |
} | |
public Task<T> PostAsync<T>(string endpoint, object content) | |
{ | |
var httpContent = | |
new StringContent(JsonConvert.SerializeObject(content), Encoding.UTF8, "application/json"); | |
return Invoke( | |
client => client.PostAsync(endpoint, httpContent), | |
async message => JsonConvert.DeserializeObject<T>(await message.Content.ReadAsStringAsync()) | |
); | |
} | |
public Task<T> PutAsync<T>(string endpoint, object content) | |
{ | |
var httpContent = | |
new StringContent(JsonConvert.SerializeObject(content), Encoding.UTF8, "application/json"); | |
return Invoke( | |
client => client.PutAsync(endpoint, httpContent), | |
async message => JsonConvert.DeserializeObject<T>(await message.Content.ReadAsStringAsync()) | |
); | |
} | |
public async Task<T> PostAsyncAsFormEncoded<T>(string endpoint, object content) | |
{ | |
var request = new HttpRequestMessage(HttpMethod.Post, endpoint); | |
var form = new FormUrlEncodedContent(content.ToKeyValue()); | |
request.Content = form; | |
var response = await _client.SendAsync(request); | |
if (response.IsSuccessStatusCode) return await response.Content.ReadAsAsync<T>(); | |
var exception = new Exception(await response.Content.ReadAsStringAsync()); | |
exception.Data.Add("StatusCode", (int) response.StatusCode); | |
throw exception; | |
} | |
private async Task<T> Invoke<T>( | |
Func<HttpClient, Task<HttpResponseMessage>> operation, | |
Func<HttpResponseMessage, Task<T>> actionOnResponse) | |
{ | |
_client.DefaultRequestHeaders.Add("Shop-Id", Environment.GetEnvironmentVariable("SHOPNUMBER")); | |
if (!string.IsNullOrWhiteSpace(AppService.HttpContext_Current.Session.GetString("CartID"))) | |
{ | |
_client.DefaultRequestHeaders.Add("Cart-Id", | |
AppService.HttpContext_Current.Session.GetString("CartID")); | |
} | |
var bearer = AppService.HttpContext_Current.User.Claims.FirstOrDefault(x => x.Type == "Bearer")?.Value; | |
if (bearer != null) | |
{ | |
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearer); | |
} | |
var response = await operation(_client).ConfigureAwait(false); | |
if (response.IsSuccessStatusCode) | |
return await actionOnResponse(response).ConfigureAwait(false); | |
var exception = new Exception(await response.Content.ReadAsStringAsync()); | |
exception.Data.Add("StatusCode", (int) response.StatusCode); | |
throw exception; | |
} | |
public void Dispose() | |
{ | |
//_client?.Dispose(); | |
GC.SuppressFinalize(this); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment