【问题标题】:Encrypt URL parameter return NULL issue加密 URL 参数返回 NULL 问题
【发布时间】:2021-10-22 14:51:36
【问题描述】:

我正在尝试在 ASP.NET 中加密 URL 参数 ID。我用IDataProtector 构建了一个简单的项目。 但我在示例代码中指向的行中收到 Null 引用错误。

控制器:

 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();
    }

【问题讨论】:

  • 你没有提到错误是什么。还有DataPro dataProobj = new DataPro(); ID 在哪里设置?
  • 尊敬的 Rahatur 感谢您的回复,代码中作为注释提到的问题,请查看代码,问题返回 null ,DataPro 是模型类
  • 我可以看到创建对象后没有分配ID属性。能否确认dataProobj.id.ToString() 不为空?
  • 我调试dataProobj.id.ToString()返回12131,dataProobj.encID行的问题,程序停在这里

标签: c# asp.net asp.net-mvc encryption qr-code


【解决方案1】:

Protect 函数也将字符串作为参数。因此无需将 Id 转换为字节。 将Index 中的代码更改为如下:

using Microsoft.AspNetCore.DataProtection;

...
dataProobj.encID = protector.Protect(dataProobj.id.ToString());
...

这对我有用。

【讨论】:

  • 感谢 Rahatur 的努力,dataProobj.id.ToString() 显示错误“无法从字符串转换为字节[]”
  • 我搜索了很多这个问题,但我没有找到任何答案,是否有任何我应该安装或调用的包,或者缺少什么?
  • @AsmaAlghamdi 添加来自 Nuget 管理器的 Microsoft.AspNetCore.DataProtection
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-14
  • 2020-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多