Marcelo C Fernandes Marcelo C Fernandes - 3 months ago 20
C# Question

Encrypt value null c#

I´m with a problem... How i am a newbie, i HAD this code and i am trying fix it:

string nomePesquisa = entryNmPesq.Text;

var nomePesqCripto = Crypto.EncryptAes(nomePesquisa, hash, salt);
string nomepesquisa = Uri.EscapeDataString(Convert.ToBase64String(nomePesqCripto));

ApiCall apiCall = new ApiCall();

apiCall.GetResponse<List<Envolvido>>("nomes", "Envolvidos", nomepesquisa)


Sometimes the value of "nomepesquisa" is null and i get a error on Encripty. So, i am trying to do this:

if (nomePesquisa != null)
{
var nomePesqCripto = Crypto.EncryptAes(nomePesquisa, hash, salt);
string nomepesquisa = Uri.EscapeDataString(Convert.ToBase64String(nomePesqCripto));
}
else { string nomepesquisa = null; }


But the "nomepesquisa" is not detected because are inside of the IF and stay underlined .
My question is: Sometimes the value will be Null and i don´t want to Encripty...in this case, i want to pass the value "nomepesquisa" on apiCall.GetResponse ! Now, because of the IF, the "nomepesquisa" is not detected.

Answer

I'm not sure what you're trying to achieve, but your if is in the wrong place. I presume that you want to skip the API call if the value is null/empty? Then this is what you should do:

string nomePesquisa = entryNmPesq.Text;

var nomePesqCripto = Crypto.EncryptAes(nomePesquisa, hash, salt);
string nomepesquisa = Uri.EscapeDataString(Convert.ToBase64String(nomePesqCripto));

if (!String.IsNullOrEmpty(nomepesquisa))
{
    ApiCall apiCall = new ApiCall();
    apiCall.GetResponse<List<Envolvido>>("nomes", "Envolvidos", nomepesquisa);
}

The real question is why nomepesquisa can be empty or null in the first place?


So what I understand from your edit: When there's input in entryNmPesq your want to encrypt it and send it to the API call. When there's no input, you want to send an empty string?

string nomePesquisa = entryNmPesq.Text;
string nomeApiCall = String.Empty;

if (!String.IsNullOrEmpty(nomePesquisa))
{
  var nomePesqCripto = Crypto.EncryptAes(nomePesquisa, hash, salt);
  nomeApiCall = Uri.EscapeDataString(Convert.ToBase64String(nomePesqCripto));
}

ApiCall apiCall = new ApiCall();
apiCall.GetResponse<List<Envolvido>>("nomes", "Envolvidos", nomeApiCall);
Comments