0

I have a problem which is really frustrating me and I'm having trouble solving it. My team has assembled a small solution in C# which should send a file to an API. File is being sent via HTTP post request.

Solution consists of a service which sends the file and API which receives it. When both service and API are on the same computer it works perfectly but when API is deployed on the server it fails to receive the file. Receiving code is simple:

public HttpResponseMessage Post()
    {
    httpResponseMessage result = null;
    var httpRequest = HttpContext.Current.Request;
    //do sth with the file set response
    return response;
    }

request is received but the problem is when I access

httpRequest.Files

it is empty. As sugested by microsoft documentation this should be autopopulated with files in multipart/form-data type. When I call

httpRequest.ContentLength

it is exactly what was sent and

httpRequest.ContentType

multipart/form-data;

So data is received but API does not recognize the files. Is there any way to get API to recognize the files, and if not is there any manual way to parse the files from the response body.

Touki
  • 7,465
  • 3
  • 41
  • 63
Ivan Kvolik
  • 401
  • 6
  • 16

1 Answers1

0

With some help from Kristers post i managed to solve ma issue. Post method now looks this way:

public async Task<HttpResponseMessage> Post()
{
    HttpResponseMessage result = null;
    if (Request.Content.IsMimeMultipartContent())
        {
            try
            {
                var provider = new MultipartFormDataStreamProvider(fileManager.TemporaryFilePath);
                await Request.Content.ReadAsMultipartAsync(provider);
                      foreach (MultipartFileData file in provider.FileData)
                      {
                           logger.Info(string.Format("Uploaded file: {0}\n on path {1}", file.Headers.ContentDisposition.FileName, file.LocalFileName));
                           //do sth with the file
                      }
                //Do sth else
            }
        }
}

Also not that files you get this way are not saved in their original name, but rather in random caracters name with no file extension:

file.LocalFileName

Source filename is available in the following property:

file.Headers.ContentDisposition.FileName

This way you can rename the received file to its original name.

Ivan Kvolik
  • 401
  • 6
  • 16