Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate the size of a HttpRequestMessage?

Tags:

json

c#

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.

like image 623
desautelsj Avatar asked Oct 01 '17 02:10

desautelsj


1 Answers

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;
}
like image 110
Alexandre TRINDADE Avatar answered Oct 16 '22 01:10

Alexandre TRINDADE