asp.net-mvc – MVC 3 – 仅限特定用户访问

在我的Web应用程序中,注册用户可以添加内容并在以后进行编辑.我只希望内容的作者能够编辑它.除了在检查记录的用户是否与作者相同的所有操作方法中手动编写代码之外,还有其他智能方法吗?我可以用于整个控制器的任何属性

解决方法

Any attribute that I Could use for the whole controller?

是的,您可以使用自定义属性扩展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
}

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....