2012-04-08 82 views
4

在我的Web應用程序中,註冊用戶可以添加新內容並稍後進行編輯。我只希望內容的作者能夠編輯它。除了在所有檢查記錄的用戶是否與作者相同的操作方法中手動編寫代碼之外,是否有任何智能的方法來執行此操作?我可以使用整個控制器的任何屬性?MVC 3 - 僅限特定用戶訪問

+3

控制器或動作屬性不會有個別文章的上下文和作者,一般是誰登錄的。你最好將作者與發佈的動作進行比較,以尋找一個可以處理它的屬性。 – 2012-04-08 17:10:32

回答

6

我可以用於整個控制器的任何屬性?

public class AuthorizeAuthorAttribute : AuthorizeAttribute 
{ 
    protected override bool AuthorizeCore(HttpContextBase httpContext) 
    { 
     var isAuthorized = base.AuthorizeCore(httpContext); 
     if (!isAuthorized) 
     { 
      // the user is either not authenticated or 
      // not in roles => no need to continue any further 
      return false; 
     } 

     // get the currently logged on user 
     var username = httpContext.User.Identity.Name; 

     // get the id of the article that he is trying to manipulate 
     // from the route data (this assumes that the id is passed as a route 
     // data parameter: /foo/edit/123). If this is not the case and you 
     // are using query string parameters you could fetch the id using the Request 
     var id = httpContext.Request.RequestContext.RouteData.Values["id"] as string; 

     // Now that we have the current user and the id of the article he 
     // is trying to manipualte all that's left is go ahead and look in 
     // our database to see if this user is the owner of the article 
     return IsUserOwnerOfArticle(username, id); 
    } 

    private bool IsUserOwnerOfArticle(string username, string articleId) 
    { 
     throw new NotImplementedException(); 
    } 
} 

然後:

是的,你可以用自定義的擴展Authorize屬性

[HttpPost] 
[AuthorizeAuthor] 
public ActionResult Edit(int id) 
{ 
    ... perform the edit 
} 
0

我想:

  1. 保存db.aspnet_Users columm用戶ID(GUID)對內容記錄
  2. 寫你的內容模型的擴展方法,從而驗證GUID對保存的內容,用戶的Guid當前用戶
  3. 我會寫一些代碼覆蓋您的管理員登錄功能(我會創建一個管理員角色)。
相關問題