Pagseguro Session with Asp.Net MVC?

Asked

Viewed 110 times

0

I am trying to get the Pagseguro session using the Asp.Net MVC Webclient but always launches an error exception that I am unable to solve.

Webclient

[HttpPost]
        public JsonResult getSessaoPagSeguro() {

            try{
                //URI de sessao.
                string uri = PagSeguroCfg.PAGSEG_SANDBOX_SESSION;

                //Conjunto de parâmetros/formData.
                System.Collections.Specialized.NameValueCollection postData = new System.Collections.Specialized.NameValueCollection();
                postData.Add("email", PagSeguroCfg.PAGSEG_LOGIN);
                postData.Add("token", PagSeguroCfg.PAGSEG_SANDBOX_TOKEN);

                //String que receberá o XML de retorno.
                string xmlString = null;

                //Webclient faz o post para o servidor de pagseguro.
                using (WebClient wc = new WebClient())
                {
                    //Informa header sobre URL.
                    wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded;charset=ISO-8859-1");

                    //Faz o POST e retorna o XML contendo resposta do servidor do pagseguro.
                    byte[] result = wc.UploadValues(uri, postData);

                    //Obtém string do XML.
                    xmlString = Encoding.ASCII.GetString(result);
                }

                //Cria documento XML.
                XmlDocument xmlDoc = new XmlDocument();

                //Carrega documento XML por string.
                xmlDoc.LoadXml(xmlString);

                //Obtém código de transação (Checkout).
                var code = xmlDoc.GetElementsByTagName("id")[0];

                jsonResposta.Add("session", code.InnerText);

            }catch(Exception e){
                Debug.WriteLine(e.Message);
            }

            return Json(jsonResposta);
        }

Exception

Exception thrown: 'System.Net.WebException' in System.dll
O cabeçalho de Content-Type não pode ser alterado de seu valor padrão para esta solicitação.

1 answer

1


According to the microsoft documentation, it is recommended to use the Httpclient:

! Important

It is not recommended that you use the Webclient class for new development. Instead, use the System.Net.Http.Httpclient class.

But for your problem. In the next line you are using Header:

//Informa header sobre URL.
wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded;charset=ISO-8859-1");

To API documentation pagseguro explains, that the header for an XML request is different from HTTP:

The Content-Type header should be reported as in the example below:

Content-Type: application/xml; charset=ISO-8859-1

Note: If your app or store does not use the set of ISO-8859-1 characters, e.g. (UTF-8), it is necessary to replace the charset parameter of the above example.

Browser other questions tagged

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