Skip to content

Instantly share code, notes, and snippets.

@TechWatching
Created January 28, 2020 13:05
Show Gist options
  • Save TechWatching/337f610109a2ffd7fad5214045693001 to your computer and use it in GitHub Desktop.
Save TechWatching/337f610109a2ffd7fad5214045693001 to your computer and use it in GitHub Desktop.
public class UserService : IUserService
{
private readonly HttpClient _httpClient;
public UserService(HttpClient httpClient)
{
_httpClient = httpClient;
}
public async Task<IReadOnlyCollection<User>> GetAllUsers()
{
var token = await RetrieveToken();
var request = new HttpRequestMessage(HttpMethod.Get, "user");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
var response = await _httpClient.SendAsync(request);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsAsync<IReadOnlyCollection<User>>();
}
public async Task UpdateUser(User userToUpdate)
{
var token = await RetrieveToken();
var request = new HttpRequestMessage(HttpMethod.Put, $"user/{userToUpdate.Name}");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
request.Content = new StringContent(JsonConvert.SerializeObject(userToUpdate));
var response = await _httpClient.SendAsync(request);
response.EnsureSuccessStatusCode();
}
private async Task<string> RetrieveToken()
{
var body = new { login = "login", password = "password" };
var response = await _httpClient.PostAsync("login", new StringContent(JsonConvert.SerializeObject(body)));
var authResponse = await response.Content.ReadAsAsync<AuthResponse>();
return authResponse.Token;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment