繁体   English   中英

模型绑定程序以解密字符串并将其转换为int

[英]Model binder to decrypt string and convert to int

我有一个模型,其属性idint类型。

我在URL中传递了id ,例如Detail/20以获取数据。 但是,现在我的客户说他们不想看到id ,因为任何人都可以修改并查看其他记录。

现在,我决定对其进行加密和解密,并将其分配给另一个属性: encId

public ActionResult List()
{
    foreach(Employee e in empList)
    {
        e.encId = MyUtil.Encrypt(id,"sessionid");    
    }

    return View(empList);
}

最后,我将自己的网址设置为Detail/WOgV16ZKsShQY4nF3REcNQ==/

现在,我所需要做的就是将其解密回原始形式,并将其分配给int类型的属性id

public ActionResult Detail(int id) //don't want (string id)
{

}

如何编写解密并转换为有效id模型资料夹? 同样,如果发生任何错误/异常,它也必须重定向到404错误页面。 当用户手动编辑url(加密的ID)中一些无用的文本时,可能会发生这种情况。

首先,这不是确保网站和数据安全的方法。 请看一下“ 通过隐蔽性实现安全性 ”问题。 您最好在每个员工记录上定义权限集,以及可以或不能编辑它们的权限。 这样的例子可能看起来像这样:

public ActionResult Detail(int id)
{
    if(MySecurityProvider.CanView(id, HttpContext.Current.User.Identity.Name){
        return View();
    }
    Return RedirectToAction("PermissionIssue", "Errors");
}

话虽如此,要继续您的工作,只需在操作结果内进行解密即可。

public ActionResult Detail(string Id)
{
    int actualId;
    try{
       actualId = MyUtil.Decrypt(id);
    }catch(Exception e){
         //someone mucked with my encryption string
         RedirectToAction("SomeError", "Errors");
    }
    var employee = MyEmployeeService.GetEmployeeById(actualId);
    if(employee == null){
         //This was a bad id
         RedirectToAction("NotFound", "Errors");
    }
    Return View(employee);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM