Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

230
Visualizações
HttpContent boundary double quotes

I have this code sample that was posted as an answer to another question (Send a file via HTTP POST with C#). It works fine except for one issue. It surrounds the boundary in the HTTP header with double quotes:

multipart/form-data; boundary="04982073-787d-414b-a0d2-8e8a1137e145"

This is choking the webservice that I'm trying to call. Browsers don't have those double quotes. I need some way to tell .NET to leave them off.

private System.IO.Stream Upload(string actionUrl, string paramString, Stream paramFileStream, byte [] paramFileBytes)
{
    HttpContent stringContent = new StringContent(paramString);
    HttpContent fileStreamContent = new StreamContent(paramFileStream);
    HttpContent bytesContent = new ByteArrayContent(paramFileBytes);
    using (var client = new HttpClient())
    using (var formData = new MultipartFormDataContent())
    {
        formData.Add(stringContent, "param1", "param1");
        formData.Add(fileStreamContent, "file1", "file1");
        formData.Add(bytesContent, "file2", "file2");
        var response = client.PostAsync(actionUrl, formData).Result;
        if (!response.IsSuccessStatusCode)
        {
            return null;
        }
        return response.Content.ReadAsStreamAsync().Result;
    }
}
over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

You can remove the quotes from the boundary by using the following code:

var boundary = formData.Headers.ContentType.Parameters.First(o => o.Name == "boundary"); 
boundary.Value = boundary.Value.Replace("\"", String.Empty);    
over 4 years ago · Santiago Trujillo Relatório

0

Expanding on the dicsussion in a similar issue in the dotnet runtime repo. Choosing to not have quotes involves two steps

  1. choose your own non-quoted boundary
  2. remove auto-generated ContentType header with one with no quotes
private System.IO.Stream Upload(string actionUrl, string paramString, Stream paramFileStream, byte [] paramFileBytes)
{
    HttpContent stringContent = new StringContent(paramString);
    HttpContent fileStreamContent = new StreamContent(paramFileStream);
    HttpContent bytesContent = new ByteArrayContent(paramFileBytes);
    //Set your own boundary, otherwise the internal boundary between multiple parts remains with quotes
    string boundaryDelimiter = String.Format("----------{0}", DateTime.Now.Ticks.ToString("x"));
    using (var client = new HttpClient())
    using (var formData = new MultipartFormDataContent(boundaryDelimiter))
    {
        formData.Add(stringContent, "param1", "param1");
        formData.Add(fileStreamContent, "file1", "file1");
        formData.Add(bytesContent, "file2", "file2");
        //remove quotes from ContentType Header
        _multiPartContent.Headers.Remove("Content-Type");
        _multiPartContent.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=" + boundaryDelimiter);

        var response = client.PostAsync(actionUrl, formData).Result;
        if (!response.IsSuccessStatusCode)
        {
            return null;
        }
        return response.Content.ReadAsStreamAsync().Result;
    }
}
over 4 years ago · Santiago Trujillo Relatório

0

This is an old question but I had the same problem and solved the same way pointed out by @Luis Perez in his answer but using that has the drawback that MultipartContent stops calculating content size so this was my solution:

var multipartContent = new MultipartFormDataContent();
var boundaryParameter = multipartContent.Headers.ContentType
                                        .Parameters.Single(p => p.Name == "boundary");
boundaryParameter.Value = boundaryParameter.Value.Replace("\"", "");

// --- Put the rest of content here

var size = (await multipartContent.ReadAsStreamAsync()).Length;
multipartContent.Headers.ContentLength = size;

Hope this helps someone out there.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda