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