Search code examples
c#asp.netasp.net-mvcencryptionqr-code

Encrypt URL parameter return NULL issue


I'm trying to encrypt URL parameter ID in ASP.NET. I have built a simple project with IDataProtector. But I am getting a Null reference error in the line pointed in the sample code.

Controller:

 private readonly IDataProtector protector;

    public QRScanningController(IDataProtectionProvider dataProtectionProvider, DataPro dataPro)
    {          
            protector = dataProtectionProvider.Create(dataPro.EmpIdRoutValue);            
    }

    public QRScanningController()
    {
        //protector = dataProtectionProvider.Create(dataPro.EmpIdRoutValue);
    }
    
    public ActionResult Index()
    {
        
        DataPro dataProobj = new DataPro();
        dataProobj.id = 12131;
        dataProobj.encID = protector.Protect(Encoding.ASCII.GetBytes(dataProobj.id.ToString())); **//the issue in this line return Null value.**
        return View(dataProobj);
    }

    public ActionResult QRscan(string encID)
    {

        return View();
    }

Solution

  • The Protect function also takes a string as a parameter. So no need to convert the Id to a byte. Change your code in the Index to be as followings:

    using Microsoft.AspNetCore.DataProtection;
    
    ...
    dataProobj.encID = protector.Protect(dataProobj.id.ToString());
    ...
    

    That worked for me.

    enter image description here