2013-11-21 29 views
0

我有一個模型,它有一個屬性id類型int模型聯編程序解密字符串並轉換爲int

我通過id在像Detail/20這樣的URL來獲取數據。但是,現在我的客戶說他們不想看到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中的無用文本(加密標識)時可能會發生這種情況。

+2

1)爲什麼不使用適當的授權來防止用戶訪問/修改他們不應該能夠訪問的記錄? 2)而且,如果你想加密/解密,你爲什麼不在控制器動作中進行解密? – ataravati

回答

1

首先,這不是保護您的網站和數據的方法。請看Security Through Obscurity的問題。您最好定義每個員工記錄上的權限集以及誰可以編輯或不能編輯它們。這樣的例子可能是這樣的:

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