我有我的操作方法
[Authorize(Roles="Admin")]
public ActionResult EditPosts(int id)
{
return View();
}在我的情况下,我需要授权管理员,以便他们可以编辑帖子,但(这里是很酷的部分),我还需要允许帖子的创建者能够编辑普通用户的帖子。那么,我如何过滤掉创建帖子的用户和管理员,而让其他用户保持未授权状态?我收到了PostEntry id作为路由参数,但这是在属性之后,属性也只接受常量参数,看起来很困难,你的回答非常感谢,干杯!
发布于 2012-07-16 01:30:43
您可以编写一个自定义的authorize属性:
public class AuthorizeAdminOrOwnerOfPostAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var authorized = base.AuthorizeCore(httpContext);
if (!authorized)
{
// The user is not authenticated
return false;
}
var user = httpContext.User;
if (user.IsInRole("Admin"))
{
// Administrator => let him in
return true;
}
var rd = httpContext.Request.RequestContext.RouteData;
var id = rd.Values["id"] as string;
if (string.IsNullOrEmpty(id))
{
// No id was specified => we do not allow access
return false;
}
return IsOwnerOfPost(user.Identity.Name, id);
}
private bool IsOwnerOfPost(string username, string postId)
{
// TODO: you know what to do here
throw new NotImplementedException();
}
}然后用它来装饰你的控制器动作:
[AuthorizeAdminOrOwnerOfPost]
public ActionResult EditPosts(int id)
{
return View();
}https://stackoverflow.com/questions/11493873
复制相似问题