C# Httpwebrequest send Multipart/form-data in POST

Asked

Viewed 1,617 times

1

I need to send one POST using HttpWebRequest, with the header Content-Type=multipart/form-data and Accept=multipart/form-data, and the data in Body.

My routine below, I use it smoothly doing POST, sending data in format Json.

Problem

I need to put in the current routine, parameters for the multipart/form-data, and I’ve tried many ways, but none of them worked.

The data I have to send is, 3 text fields.

Current Routine

protected virtual RetornoSolicitacao Executa(Operacao operacao, string urlBase, string urlServico, string dados)
{
    HttpWebRequest requisicao = MontaRequisicao(urlBase, urlServico);           

    byte[] dadosFormatados = Encoda(dados);
    requisicao.ContentLength = dadosFormatados.Length;

    Stream requisicaoDados = requisicao.GetRequestStream();
    requisicaoDados.Write(dadosFormatados, 0, dadosFormatados.Length);
    requisicaoDados.Close();

    HttpWebResponse resposta;

    resposta = (HttpWebResponse)requisicao.GetResponse();

    resultado.HttpCodigoRetorno = (int)resposta.StatusCode;
    var respostaTexto = new StreamReader(resposta.GetResponseStream());
    resultado.Retorno = respostaTexto.ReadToEnd();
}

Requisition

protected virtual HttpWebRequest MontaRequisicao(string urlBase, string urlServico)
{
    HttpWebRequest requisicao = default(HttpWebRequest);

    Uri url = new Uri(new Uri(urlBase), urlServico);
    requisicao = (HttpWebRequest)WebRequest.Create(url);
    
    requisicao.ContentType = "multipart/form-data";
    requisicao.Accept = "multipart/form-data";                                    
    requisicao.Method = "POST";
    requisicao.Timeout = ConfiguarTimeOut(_configuracao.Configuracao) * 1000;               
    requisicao.Headers.Add("Authorization", chaveAutorizacao);               

    return requisicao;          
}
  • What’s going on? Giving error? It just doesn’t send?

  • @Francisco gives error 500 and 415. In Postman I can send, but I could not understand to put in C#

  • When that’s so I use Fiddler to capture the 2 request. So I can make the comparison

  • This site https://www.telerik.com/fiddler @Francisco

  • In the Postman on the right side of the request that this accepting has a button called "Code", checks if all the items of the header that Postman generates is equal to your C request#.

  • @Gabrielcoletta the worst I’ve ever checked him and I’m not finding the problem. Apparently it’s all the same. Now I’m testing ContentType and Accept with other types. According to this OS response it is correct how to put the data https://stackoverflow.com/questions/4256136/setting-a-webrequests-body-data. I will test and I answer now.

  • What was the result you obtained?

Show 2 more comments
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.