在我的web应用程序的注册用户可以添加新的内容,后来编辑。 我想只有内容的作者能够对其进行编辑。 难道还有比在所有的操作方法手工编写代码,如果登录用户相同笔者,检查这样其他任何聪明的办法? 我可以用于整个控制器的任何属性?
Answer 1:
我可以用于整个控制器的任何属性?
是的,你可以扩展Authorize
使用自定义的一个属性:
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();
}
}
然后:
[HttpPost]
[AuthorizeAuthor]
public ActionResult Edit(int id)
{
... perform the edit
}
Answer 2:
我会:
- 保存db.aspnet_Users columm用户ID(GUID)对内容记录
- 编写扩展方法,从而验证GUID对保存的内容,用户的Guid当前用户的内容模型
- 我会写一些代码重写此功能,您的管理员登录(我想创建一个管理员角色)。
文章来源: MVC 3 - access for specific user only