0

I'm trying to upload a file with some metadata to a Web API. Everything is fine within the developer environment. But when the same API is hosted in Azure I get the following date parsing error:

Conversion from string "31/03/2019 11:33:52" to type 'Date' is not valid.

I guess StringContent should write the date on ISO 8601 format and it does not.

Next is a simplification of my procedure:

Public Async Function UploadDocFile(oHttpClient as HttpClient, url as string, ByVal oByteArray as Byte(), exs As List(Of Exception)) As Task(Of Boolean)
    Dim retval As Boolean
    Dim formContent = New Net.Http.MultipartFormDataContent From {
        {New Net.Http.StringContent("DateCreated"), now},
        {New Net.Http.StreamContent(New IO.MemoryStream(oDocfile.Stream)), "pdf", "pdf.jpg"}
    }

    Dim response = Await oHttpClient.PostAsync(url, formContent)
    If response.StatusCode = 200 Then
        retval = True
    Else
        exs.Add(New Exception(response.ReasonPhrase))
    End If
    Return retval
End Function
Matias Masso
  • 1,670
  • 3
  • 18
  • 28
  • 1
    The parameter passed to the `StringContent` constructor should be _the value_, not _the name_. It should be `{New Net.Http.StringContent(Now.ToString("SomeFormat"), "DateCreated"}` where `SomeFormat` is the format expected by the host. – 41686d6564 stands w. Palestine Mar 31 '19 at 15:34
  • You pointed me in the right direction. Indeed, the constructor was right, but I should have specified the Sortable ("s") Format Specifier. Next code works Ok: {New Net.Http.StringContent("DateCreated"), now.toString("s")} – Matias Masso Mar 31 '19 at 16:52
  • Check my answer below. It has additional explanation and suggestions. – 41686d6564 stands w. Palestine Mar 31 '19 at 16:53

1 Answers1

1

You are using a Collection Initializer to add items to the MultipartFormDataContent; you're expected to follow this overload of the Add method, which accepts two parameters of type HttpContent and String, respectively.

Thus, the second value enclosed in the braces ({}) should be the name of the data content, not its value. On the other hand, the parameter passed to the StringContent constructor should be the value (content), not the name. You basically have them swapped out. If you'd had Option Strict set to On (which is something you should do, BTW), you would've gotten a compiler error and would've easily identified the mistake.

Your code should look something like this:

Dim formContent = New Net.Http.MultipartFormDataContent From
{
    {New Net.Http.StringContent(Now.ToString("SomeFormat")), "DateCreated"},
    ' More values.
}

..where SomeFormat is a format supported by the web API that you're using.