1

I am getting error while trying to Post stream to a web API method, the reason I understand that it may be thrown if the file being streamed is being written at the same time.

When file is not being written at the same time, then I am not getting this error.

Bytes to be written to the stream exceed the Content-Length bytes size specified.

I am trying to suppress it by using ProtocolViolationException, but still I am getting this error.

What could be the reason and how to suppress it or a way to handle it?

Client Code

 using (var client = new HttpClient())
            {
                response = await client.PostAsync(endpoint, new StreamContent(fileStream));
            }

Server Code (Asp.Net Web API)

try
            {
                using (FileStream fs = new FileStream(filePath, FileMode.CreateNew, FileAccess.Write))
                {
                    await Request.Content.CopyToAsync(fs);
                }
            }
            catch (ProtocolViolationException protocolViolationException)
            {
                //supress error
            }
            catch (Exception ex)
            {
                throw ex;
            }

Note - While debug I found that for web API code, the 2nd catch block hit and the error message is The client disconnected.

user584018
  • 10,186
  • 15
  • 74
  • 160

1 Answers1

0

I got the solution. I need to move ProtocolViolationException catch into client side rather than server side.

try
  {
    using (var client = new HttpClient())
        {
            response = await client.PostAsync(endpoint, new StreamContent(fileStream));
        }
 }
 catch (ProtocolViolationException protocolViolationException)
        {
            //supress error
        }
user584018
  • 10,186
  • 15
  • 74
  • 160