Andrey Bushman
Andrey Bushman

Reputation: 12476

Post big data through HTTP protocol

ASP.NET Core MVC 2

I need to send the binary data to server. Data size often can be big but not more than 1 Gb. This is my attempt to do it:

var client = new HttpClient();

using (FileStream fs = new FileStream(fileName, FileMode.Open))
{
    fs.Position = 0;
    byte[] bytes = new byte[fs.Length];
    fs.Read(bytes, 0, (int) fs.Length);

    ByteArrayContent content = new ByteArrayContent(bytes);
    content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
    content.Headers.ContentLength = fs.Length;

    var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost:5000/Home/Upload");
    request.Content = content;

    try
    {
        HttpResponseMessage response = await client.SendAsync(request);
        Console.WriteLine("Response status code: {0}", response.StatusCode);
    }
    catch (Exception ex)
    {
        Console.WriteLine("Exception: {0}", ex.Message);
    }
}

In the debug mode I try to send 27Mb data. In the row

HttpResponseMessage response = await client.SendAsync(request);

the breakpoint works, but after this nothing happen: the breackpoints for

Console.WriteLine("Response status code: {0}", response.StatusCode);

and

Console.WriteLine("Exception: {0}", ex.Message);

don't work. Application silently finished.

What I did wrong?

Upvotes: 0

Views: 500

Answers (1)

Rudresha Parameshappa
Rudresha Parameshappa

Reputation: 3926

No need to use ByArrayContent, just use StreamContent with PostAsync.

remove following code

fs.Position = 0;
byte[] bytes = new byte[fs.Length];
fs.Read(bytes, 0, (int) fs.Length);

ByteArrayContent content = new ByteArrayContent(bytes);
content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
content.Headers.ContentLength = fs.Length;

var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost:5000/Home/Upload");
request.Content = content;

try
{
    HttpResponseMessage response = await client.SendAsync(request);

Replace with below code as HttpClient contains PostAsync we can use

try
{
     HttpResponseMessage response = await client.PostAsync("http://localhost:5000/Home/Upload", new StreamContent(fs));

Upvotes: 1

Related Questions