Last active
July 31, 2019 08:49
-
-
Save vabka/7cd2c5100e50274364612c6d7ba6244b 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
public static class HttpClientHelpers | |
{ | |
public static async Task<RestResponse<TResult>> PostJsonAsync<TResult>(this HttpClient client, | |
string resource, | |
object requestBody) | |
{ | |
var json = requestBody != null ? JsonConvert.SerializeObject(requestBody) : string.Empty; | |
var request = new StringContent(json, Encoding.UTF8, "application/json"); | |
var response = await client.PostAsync(resource, request); | |
return await RestResponse<TResult>.FromHttpResponseMessageAsync(response); | |
} | |
} | |
public class RestResponse<T> | |
{ | |
public static async Task<RestResponse<T>> FromHttpResponseMessageAsync(HttpResponseMessage response) | |
=> new RestResponse<T>(await response.Content.ReadAsStringAsync(), response.StatusCode); | |
private RestResponse(string responseBody, HttpStatusCode statusCode) | |
{ | |
ResponseBody = responseBody; | |
if(responseBody != null) | |
Result = JsonConvert.DeserializeObject<T>(responseBody); | |
StatusCode = statusCode; | |
IsSuccessStatusCode = statusCode.IsSuccessful(); | |
} | |
public string ResponseBody { get; } | |
public HttpStatusCode StatusCode { get; } | |
public T Result { get; } | |
public bool IsSuccessStatusCode { get; } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment