Implementing Network Data Push Mechanisms in C#
Standard HTTP POST Implementation
The following utility method handles generic JSON data transmission. It constructs the request URI by appending an optional access token as a query parameter. The implementation ensures UTF-8 encoding for the content payload and handles basic error serialization.
private async Task<string> DispatchPayloadAsync(string endpoint, string jsonData, string authToken = null)
{
var targetUrl = endpoint;
if (!string.IsNullOrEmpty(authToken))
{
targetUrl += "?access_token=" + authToken;
}
using var httpClient = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, targetUrl);
request.Content = new StringContent(jsonData, Encoding.UTF8, "application/json");
try
{
var response = await httpClient.SendAsync(request).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsStringAsync().ConfigureAwait(false);
}
var errorResult = new { ErrorCode = -999999, Message = response.StatusCode.ToString() };
return JsonConvert.SerializeObject(errorResult);
}
catch (Exception ex)
{
return $"Request failed for endpoint {{{endpoint}}}. Details: {ex.Message}";
}
}Secure Data Transmission with Bearer Tokens
This implementation demonstrates a secure data push mechanism using IHttpClientFactory. It is designed for APIs requiring OAuth 2.0 Bearer token authentication, injected into the request headers. This approach is recommended for maintaining socket exhaustion prevention and proper DNS updates in long-running applications.
private readonly IHttpClientFactory _clientFactory;
public async Task<string> SendSecureRequestAsync(string apiUrl, string payload, string bearerToken)
{
var requestMessage = new HttpRequestMessage(HttpMethod.Post, apiUrl);
requestMessage.Content = new StringContent(payload, Encoding.UTF8, "application/json");
try
{
var httpClient = _clientFactory.CreateClient("SecureApiClient");
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearerToken);
var httpResponse = await httpClient.SendAsync(requestMessage).ConfigureAwait(false);
if (httpResponse.IsSuccessStatusCode)
{
return await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else
{
var failureResponse = new { Status = -999999, Error = httpResponse.StatusCode };
return JsonConvert.SerializeObject(failureResponse);
}
}
catch (Exception ex)
{
// Log exception details here if necessary
return $"Secure transmission error for {apiUrl}: {ex.StackTrace}";
}
}