Say I have a HttpRequestMessage object built like this:
var request = new HttpRequestMessage(HttpMethod.Post, uploadUrl)
{
Content = new ObjectContent(myObject, new JsonMediaTypeFormatter())
};
Which I will send like so:
using (var client = new HttpClient())
{
var response = await client.SendAsync(request, cancellationToken).ConfigureAwait(false);
}
Is there a way to calculate the size (in bytes) of the request payload before POSTing it? The reason I ask, is because I will be submitting this request to a 3rd party API and I know the API will reject my request if it exceeds a pre-determined max size. I figured if I could calculate the size of the payload in the request I could avoid posting requests that exceed this max size.
I use :
requestMessage.Headers.ToString().Length + // Header Length
(requestMessage.Content?.Headers.ContentLength ?? 0); // Content Length
You can also read content data and calculate size of it :
public async Task<long> GetRequestSizeAsync(HttpRequestMessage requestMessage)
{
var reader = requestMessage.Headers.ToString();
var content = await requestMessage.Content.ReadAsStringAsync();
return reader.Length + content.Length;
}
Sync version:
public long GetRequestSize(HttpRequestMessage requestMessage)
{
var reader = requestMessage.Headers.ToString();
var content = requestMessage.Content.ReadAsStringAsync().Result;
return reader.Length + content.Length;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With