Last active
November 29, 2019 06:53
-
-
Save escalonn/cfb9cdc6369ffdca7c8d8f70aac32bc0 to your computer and use it in GitHub Desktop.
This file contains hidden or 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.Net.Http; | |
using System.Text; | |
using System.Text.Json; | |
using System.Threading.Tasks; | |
using KitchenSite.Ui.Models; | |
using Microsoft.Extensions.Configuration; | |
namespace KitchenSite.Ui.Services | |
{ | |
public class FridgeService | |
{ | |
private readonly HttpClient _client; | |
private readonly JsonSerializerOptions _jsonOptions = new JsonSerializerOptions | |
{ | |
PropertyNamingPolicy = JsonNamingPolicy.CamelCase | |
}; | |
public FridgeService(HttpClient client, IConfiguration configuration) | |
{ | |
client.BaseAddress = new Uri(configuration["AppServices:Address"]); | |
client.DefaultRequestHeaders.Add("Accept", "application/json"); | |
_client = client; | |
} | |
public async Task CreateFridgeItemAsync(FridgeItem item) | |
{ | |
using var response = await SendRequestAsync(HttpMethod.Post, "/fridgeitems", item); | |
response.EnsureSuccessStatusCode(); | |
var newItem = await ReadResponseBodyAsync<FridgeItem>(response); | |
} | |
private async Task<HttpResponseMessage> SendRequestAsync<T>(HttpMethod method, string uri, T body = null) where T : class | |
{ | |
using var request = new HttpRequestMessage(method, uri); | |
if (body is T) | |
{ | |
var json = JsonSerializer.Serialize(body, _jsonOptions); | |
var content = new StringContent(json, Encoding.Default, "application/json"); | |
request.Content = content; | |
} | |
return await _client.SendAsync(request); | |
} | |
private async Task<T> ReadResponseBodyAsync<T>(HttpResponseMessage response) | |
{ | |
using var stream = await response.Content.ReadAsStreamAsync(); | |
return await JsonSerializer.DeserializeAsync<T>(stream, _jsonOptions); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment