4
在我的Web應用程序中,註冊用戶可以添加新內容並稍後進行編輯。我只希望內容的作者能夠編輯它。除了在所有檢查記錄的用戶是否與作者相同的操作方法中手動編寫代碼之外,是否有任何智能的方法來執行此操作?我可以使用整個控制器的任何屬性?MVC 3 - 僅限特定用戶訪問
在我的Web應用程序中,註冊用戶可以添加新內容並稍後進行編輯。我只希望內容的作者能夠編輯它。除了在所有檢查記錄的用戶是否與作者相同的操作方法中手動編寫代碼之外,是否有任何智能的方法來執行此操作?我可以使用整個控制器的任何屬性?MVC 3 - 僅限特定用戶訪問
我可以用於整個控制器的任何屬性?
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
}
我想:
控制器或動作屬性不會有個別文章的上下文和作者,一般是誰登錄的。你最好將作者與發佈的動作進行比較,以尋找一個可以處理它的屬性。 – 2012-04-08 17:10:32