Error while using methods to generate hash and catch MAC address

Asked

Viewed 69 times

-1

According to my question, in the Gypsy’s response to hash of mac address network card just use two methods.

But in the form of using them to retrieve the data and do the check I’m having an error:

A field initializer cannot Reference that non-static field, method, or propety

Remembering here that the way to use is: var chave = GetSHA1HashData(GetMacAddress());

I wonder if someone could help me ?

Here the methods in question to facilitate:

  public class AutenticacaoController : Controller
    {
    private EntidadesContexto db;
    string chave = GetSHA1HashData(GetMacAddress());

    public AutenticacaoController()
    {
        db = new EntidadesContexto();
    }
    protected override void Dispose(bool disposing)
    {
        if (db != null) db.Dispose();
        base.Dispose(disposing);
    }
    // GET: Autenticacao
    public ActionResult Index()
    {
        return View();
    }
    [HttpPost]
    public ActionResult Index(String Login, String Senha)
    {
        //verificando login pelo usuario do banco de dados ...
        Usuario login = db.Usuarios.Where(x => x.Login == Login && x.Senha == Senha).FirstOrDefault();
        if (login != null)
        {
            FormsAuthentication.SetAuthCookie(login.Nome.ToString(), false);
            Session.Add(".PermissionCookie", login.Perfil);
            Session.Add("UsuarioID", login.UsuarioID);
            return RedirectToAction("Index", "Home"); //pagina padrao para todos os usuarios...
        }
        return RedirectToAction("Index");

    }
    public ActionResult Sair()
    {

        FormsAuthentication.SignOut();
        Session.Remove(".PermissionCookie");
        return RedirectToAction("Index");
    }

    //Aqui são métodos para pegar o endereço MAC da placa de rede do computador e a considerá-la como chave de licença
    private string GetSHA1HashData(string data)
    {
        SHA1 sha1 = SHA1.Create();

        byte[] hashData = sha1.ComputeHash(Encoding.Default.GetBytes(data));

        StringBuilder returnValue = new StringBuilder();

        for (int i = 0; i < hashData.Length; i++)
        {
            returnValue.Append(hashData[i].ToString());
        }

        return returnValue.ToString();
    }

    private string GetMacAddress()
    {
        string macAddresses = string.Empty;

        foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
        {
            if (nic.OperationalStatus == OperationalStatus.Up)
            {
                macAddresses += nic.GetPhysicalAddress().ToString();
                break;
            }
        }

        return macAddresses;
    }
    //Aqui termina
  • I don’t know what you’re doing, where you’re making this mistake. Provide information that helps you respond.

  • Done @bigown... And this giving wrong time to use them: var key = Getsha1hashdata(Getmacaddress();. Which in case is string and not var.

  • You can send the full class code?

  • @Guillhermeportela made.

2 answers

3

Cause

The key variable is declared at class level, and therefore is a field. Fields cannot initialize (declared and defined at the same time) with a non-static value, method or property. You need to declare it at class level, and set it in the constructor.

Why?

A field can only be initialized with static members, since the instance is not defined until the constructor is executed, and direct initialization happens before any constructor is executed.

1


It will not work the way it is. You cannot create a variable initialized in the class populated by methods of the same class. In practice, it is as if the compiler does not know the methods.

There are two ways to solve:

1. Calling methods within another method

[HttpPost]
public ActionResult Index(String Login, String Senha)
{
    string chave = GetSHA1HashData(GetMacAddress());

    ...
}

2. Encapsulating methods in static classes

public static class GeradorDeLicencas
{
    public static string GetSHA1HashData(string data) { ... }
    public static string GetMacAddress() { ... }
}

Browser other questions tagged

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