Created
July 10, 2020 02:26
-
-
Save mishrsud/f0f67664ddaea5001784d7ea72ad8785 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
internal static class HttpClientExtensions | |
{ | |
public static Task<HttpResponseMessage> PostAsJsonAsync<T>(this HttpClient client, string uri, T content, string messageId = null) | |
=> SendAsJsonAsync<T>(client, HttpMethod.Post, uri, content, messageId); | |
public static Task<HttpResponseMessage> PutAsJsonAsync<T>(this HttpClient client, string uri, T content) | |
=> SendAsJsonAsync<T>(client, HttpMethod.Put, uri, content, null); | |
public static Task<HttpResponseMessage> GetAsync(this HttpClient client, string uri) | |
{ | |
var request = BuildRequest(HttpMethod.Get, uri); | |
return client.SendAsync(request); | |
} | |
private static async Task<HttpResponseMessage> SendAsJsonAsync<T>(HttpClient client, HttpMethod method, string uri, T content, string messageId = null) | |
{ | |
var request = BuildRequest(method, uri, messageId: messageId); | |
request.Content = new StringContent(JsonConvert.SerializeObject(content), Encoding.UTF8, "application/json"); | |
var response = await client.SendAsync(request); | |
return response; | |
} | |
private static HttpRequestMessage BuildRequest(HttpMethod method, string uri, string messageId = null) | |
{ | |
var request = new HttpRequestMessage(method, uri); | |
if (request.Headers.Contains("Accept") == false) | |
{ | |
request.Headers.Add("Accept", "application/json"); | |
} | |
return request; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment