我是否正在使用IDataProtector在控制器內保護和解除保護而沒有問題。我可以注入保護器並使用它。在控制器中使用c#MVC中的數據保護加密解密
IDataProtector _protector;
public HomeController(IDataProtectionProvider provider)
{
_protector = provider.CreateProtector(GetType().FullName);
}
public IActionResult Index()
{
Test test = new Test();
test.originaltext = "1";
test.encryptedtext = _protector.Protect(test.originaltext);
test.originaltext = _protector.Unprotect(test.encryptedtext);
return View(test);
}
然後,這示出了將加密和解密的「1」
我可以創建一個鏈接,並通過這個到另一個動作相同的控制器
<a asp-controller="Home"
asp-action="GetKey"
asp-route-id="@Model.encryptedtext">
Pass Key to getkey
</a>
此傳遞的加密數據上並允許我在GetKey操作中解密。
public IActionResult GetKey(String id)
{
Test test = new Test();
test.encryptedtext = id;
test.originaltext = _protector.Unprotect(id);
return View(test);
}
如果我然後嘗試創建一個鏈接並將它傳遞給另一個控制器。
<a asp-controller="Key"
asp-action="GetKeyController"
asp-route-id="@Model.encryptedtext">
Pass Key to other controller
</a>
它失敗,出現錯誤上,我應該看
System.Security.Cryptography.CryptographicException: The payload was invalid
任何線索?
在您實例創建呼叫
是剛剛發現,但謝謝你的快速反應。 – user3749535