这可以通过某种过滤器来实现,而不必在操作方法中指定吗?
当然。您可以编写自定义授权属性:
public class AuthorizeBlogPostOwnerAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var authorized = base.AuthorizeCore(httpContext);
if (!authorized)
{
return false;
}
var user = httpContext.User;
var rd = httpContext.Request.RequestContext.RouteData;
var id = rd.Values["postid"] as string;
if (string.IsNullOrEmpty(id))
{
return false;
}
return IsOwnerOfBlogPost(user.Identity.Name, id);
}
private bool IsOwnerOfPost(string username, string postId)
{
// hit your dabatase here and validate if the current user
// is owner of the blog post
throw new NotImplementedException();
}
}
可以用来装饰你的控制器动作:
[AuthorizeBlogPostOwner]
public ActionResult SomeAction(string postId)
{
... if we got that far it means that the current user is owner of the blog post
}