Implementing HTTP POST Requests with Basic Authentication Using HttpWebRequest in C#
The HttpWebRequest class enables direct manipulation of HTTP headers and request streams when transmitting data. To issue a JSON POST payload alongside Basic Authentication, configure the request object, encode the credentials, and write the serialized body to the output stream.
public string TransmitJsonPayload(string targetEndpoint, string jsonBody, string credentials)
{
var httpReq = (HttpWebRequest)WebRequest.Create(targetEndpoint);
httpReq.Method = "POST";
httpReq.ContentType = "application/json";
var encodedAuth = Convert.ToBase64String(Encoding.UTF8.GetBytes(credentials));
httpReq.Headers["Authorization"] = $"Basic {encodedAuth}";
var payloadBytes = Encoding.UTF8.GetBytes(jsonBody);
httpReq.ContentLength = payloadBytes.Length;
using (var output = httpReq.GetRequestStream())
{
output.Write(payloadBytes, 0, payloadBytes.Length);
}
using (var webResp = (HttpWebResponse)httpReq.GetResponse())
using (var respReader = new StreamReader(webResp.GetResponseStream()))
{
return respReader.ReadToEnd();
}
}
public bool ValidateOperationStatus(string serverResponse)
{
var parsed = JObject.Parse(serverResponse);
var statusValue = parsed["status"]?.ToString();
return string.Equals(statusValue, "1", StringComparison.Ordinal);
}
On the receiving service, the Authorization header must be parsed to retrieve the original credential string. The extraction logic removes the scheme prefix, decodes the Base64 segment, and returns the plaintext result.
public string DecodeBasicAuthCredentials(string authHeader)
{
if (string.IsNullOrWhiteSpace(authHeader) || !authHeader.StartsWith("Basic ", StringComparison.OrdinalIgnoreCase))
return string.Empty;
var encodedSegment = authHeader.Substring(6).Trim();
try
{
var rawBytes = Convert.FromBase64String(encodedSegment);
return Encoding.UTF8.GetString(rawBytes);
}
catch (FormatException)
{
return string.Empty;
}
}
The decoding routine safely handles missing or malformed headers. Proper disposal of HttpWebResponse and StreamReader instences via using blocks ensures that underlying TCP connections are released back to the connection pool immediately after the exchange completes.