How to configure the credentials of a webRequest?

Asked

Viewed 184 times

-1

How do I perform an ASP NET MVC 5 request in this way:

  1. Method = post;
  2. Authentication credentials = xxx:yyyyy (i.e., username, followed by two points, followed by password, encrypted in Base64 format);
  3. Send data on body webrequest in JSON format.

I’ve done several tests and I’d like to know what I might be doing wrong

NetworkCredential credential = new NetworkCredential(usernameAuth, passwordAuth, defaultURL);
CredentialCache cache = new CredentialCache();

cache.Add(new Uri(defaultURL), "Basic", credential);
            
Console.WriteLine(cache);

/*
    var unEncodedString = String.Format("{0}:{1}", usernameAuth, passwordAuth);
    var encodedString = Convert.ToBase64String(Encoding.ASCII.GetBytes(unEncodedString));
*/

try
{
    WebRequest webRequest = WebRequest.Create(defaultURL);
                
    if (webRequest != null)
    {
        //webRequest.Credentials = cache;
        webRequest.Method = "POST";
        webRequest.ContentType = "application/json";
        webRequest.ContentLength = infoDados.Length;
        webRequest.PreAuthenticate = true;
        webRequest.Credentials = cache;

        //enviando dados post
        using (var stream = webRequest.GetRequestStream())
        {
            stream.Write(infoDados, 0, infoDados.Length);
            stream.Close();
        }

        //lendo dados
        using (Stream s = webRequest.GetResponse().GetResponseStream())
        {
            using (StreamReader sr = new StreamReader(s))
            {
                result = sr.ReadToEnd();
            }
        }
    }
}
catch (Exception ex)
{
    Console.WriteLine(ex.ToString());
}

In my code:

usernameAuth: username of the authentication

passwordAuth: password for authentication

defaultURL: request submission url

  • the defaultURL variable has the full url and endpoint path? if yes, try to put in the defaultURL only the domain the application is in, the way you are creating the setting credentials is correct

  • Do you want to send credentials where? In the body of the request or in some header?

1 answer

-1


I HAVE SOMETHING SIMILAR

 var resultObjects = JObject.Parse(json);//Converto a string para o formato json
            var jsonSerializado = JsonConvert.SerializeObject(resultObjects);//Serializo meu json
            var objeto = Encoding.GetEncoding("ISO-8859-1").GetBytes(jsonSerializado);//Digo o formato do objeto para o serviço
            var requisicaoWeb = WebRequest.CreateHttp("http://meuIp/01/fwmodel/PCP0012");//Digo o caminho da minha url aonde vou estar enviando meus dados
            requisicaoWeb.Method = "POST";
            requisicaoWeb.ContentType = "application/json";//Afirmo ao servidor que estou enviando os dados no formato apllication/json
            requisicaoWeb.ContentLength = jsonSerializado.Length;//Vê o tamanho dos dados que estão sendo enviados para o servidor
            requisicaoWeb.Headers.Add("Authorization", "BASIC d3NyZXN0aW50ZXJubzpnVXVAdmxsXnZ6ajVVOUd5aW9hbnZl");//Manda para o servidor a chave para poder acessa-lo
            requisicaoWeb.Timeout = 100000000;//Seta o tempo de timeout do servidor
            using (var stream = requisicaoWeb.GetRequestStream())
            {
                stream.Write(objeto, 0, jsonSerializado.Length);//Lê o tipo do objeto e o seu tamanho para que assim o serviço entenda que dados estão chegando até ele
                stream.Close();//Fecha conexão com o servidor
            }
            try
            {
                var reposta = requisicaoWeb.GetResponse();//Caso ocorra alguma falha mostra o que está acontecendo
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            return Redirect(Request.UrlReferrer.ToString());

Browser other questions tagged

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