2011-12-02 83 views
2

新手到asp.net和mvc3。我通過設置自己的挑戰/開發應用程序來學習。我標記用戶與ProviderUserKey交互的所有記錄表。現在我希望能夠限制登錄的用戶只能編輯或刪除自己的記錄,但管理員可以編輯或刪除任何記錄。我一直在使用腳手架來生成editing` // POST控制器和視圖等。例如,代碼:/後/編輯/ 5登錄MVC3用戶只能看到自己的東西,除了管理員

[HttpPost] 
    public ActionResult Edit(PJpost pjpost) 
    { 
     if (ModelState.IsValid) 
     { 
      db.Entry(pjpost).State = EntityState.Modified; 
      db.SaveChanges(); 
      return RedirectToAction("Index"); 
     } 
     return View(pjpost); 
    }` 

任何幫助將得到高度讚賞。

回答

2

如果你有一個通用的方法編輯/動作,你想保持這種方式,我會在你的控制器somethink像ValidateOwnership(記錄)添加一個方法。此方法需要驗證CurrentUser的ID是否與記錄上的ID匹配,並且用戶是否是特定角色的成員 - 可以使用RoleManager類完成。方法將返回true/false。 準備就緒後,只需在ModelState驗證後將代碼調用放入代碼即可。它看起來像這樣

[HttpPost] 
public ActionResult Edit(PJpost pjpost) 
{ 
    if (ModelState.IsValid) 
    { 
     if(IsOwnershipValid(pjpost){ 
      db.Entry(pjpost).State = EntityState.Modified; 
      db.SaveChanges(); 
      return RedirectToAction("Index"); 
     } 
     else { 
      ModelState.AddModelError("ERROR","You're not allowed to do that"); 
      return View(pjpost); 
     } 
    } 
    return View(pjpost); 
} 

編輯: 所以OwnershipValidation看起來是這樣的:

public bool ValidateOwnership(Pjpost pjpost) { 
    if (pjpost.MemUID == Membership.GetUser().ProviderUserKey.ToString()) 
    { 
    return true; 
    } 
    else 
    { 
    return false; 
    } 
} 

我希望這是你的意思。

+0

感謝Cold和Torm。 Torm yes您的解決方案就是我的意思,但您仍然必須幫助我使用ValidateOwnership(record)'//驗證所有者 public ActionResult ValidateOwnership() { Pjpost pjpost = db.PJPost.Find(); if(pjpost.MemUID == Membership.GetUser()。ProviderUserKey.ToString()) { return true; } else { return false; } } }'看來我正在做一些非常錯誤的工作 – Diin

+0

謝謝,我得到這些錯誤返回true並返回錯誤的行:錯誤1不能隱式地將類型'bool'轉換爲'System.Web.Mvc.ActionResult ' – Diin

+0

但當然你:)方法的返回類型應該是bool而不是動作結果 - 我已經修復了示例 – torm

1

您需要查看用戶角色和授權過程,MVC會提供註冊並在其中登錄模板,包括賬戶控制器。要限制用戶訪問,您必須將角色分配給用戶。

它背後的代碼看起來像這樣。

[Authorize(Roles="admin")] 
public ActionResult admin() 
    { 
     //Action gives an admin rights since the user is in the admin role 
    return View();  
    } 

[Authorize(Roles="manager")] 
public ActionResult manager() 
    { //give a managers rights since user is im managers roles. 
    return View();  
    } 
+0

感謝@Cold的幫助 – Diin