Extension method to simplify posting with HttpClient, also an sync extension method.
public static class HttpClientExtenstion
{
public static HttpResponseMessage Post(
this HttpClient httpClient,
string requestUri,
string data,
string mediaType = "application/json")
{
var request = new HttpRequestMessage(HttpMethod.Post, requestUri)
{
Content = new StringContent(data, Encoding.UTF8, mediaType)
};
return httpClient.SendAsync(request).Result;
}
public static Task<HttpResponseMessage> PostAsync(
this HttpClient httpClient,
string requestUri,
string data,
string mediaType = "application/json")
{
var request = new HttpRequestMessage(HttpMethod.Post, requestUri)
{
Content = new StringContent(data, Encoding.UTF8, mediaType)
};
return httpClient.SendAsync(request);
}
public static Task<HttpResponseMessage> PostAsync<T>(
this HttpClient httpClient,
string requestUri,
T data,
string mediaType = "application/json")
{
var request = new HttpRequestMessage<T>(data, mediaType)
{
RequestUri = new Uri(requestUri),
Method = HttpMethod.Post
};
return httpClient.SendAsync(request);
}
}
Can be used in the following way:
var client = new HttpClient();
string contact = "{ \"ContactId\" : 1, \"Name\" : \"John Doe\"}";
var result = client.PostAsync("http://localhost:9090/api/contact", contact).Result;
Fork
0 Feedback
You must log in before you can give any feedback
You must log in before you can post a comment


788
0




Mark '.net' tag as 'like'
Mark '.net' tag as 'ignore'