j-hurst
j-hurst

Reputation: 329

Web Api Request Content Length Double the File Size

I upload a 3.5 MB file from my MVC app. When I go to send that file to my web api endpoint, I notice the request's content-length is double the size of the file (7 MB).

I tested this theory with a 5 MB file and sure enough the content-length when I went to send to the web api was 10 MB.

Below is how I am sending the file to my web api endpoint:

using (HttpClient client = new HttpClient())
{
    client.BaseAddress = new Uri(url);
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    return await client.PostAsync(requestUri, new StringContent(serializedContent, Encoding.Unicode, "application/json"));
}

I am calling this method from my MVC controller in the POST method. Why does my content-length get doubled?

UPDATE: I should note that I am using JSON.NET's JsonConvert.SerializeObject method to convert the object that contains the byte array to a string

Upvotes: 1

Views: 636

Answers (1)

TylerBrinkley
TylerBrinkley

Reputation: 1126

You're using Encoding.Unicode which uses 16-bit characters by default. If you want to save roughly half the space then use Encoding.UTF8 which uses 8-bit characters by default. Note, characters that can't be expressed in just 8-bits will use multiple bytes.

Upvotes: 2

Related Questions