【问题标题】:Controller requiring authorization only on specific parameters仅需要对特定参数进行授权的控制器
【发布时间】:2011-04-01 11:40:30
【问题描述】:

我有一个控制器,它加载一篇文章并显示它。文章有一个属性来显示它是私有的还是公共的。

如果文章是私人的,我希望用户在显示文章之前先登录。

我不能简单地将 [Authorize] 属性放在操作上,因为如果文章是公开的,则不需要授权即可显示它。

最干的方法是什么?

我想依赖默认授权模型的内置功能(如果不需要,我不想手动编写重定向和传递参数)

【问题讨论】:

    标签: asp.net-mvc-3 authorization


    【解决方案1】:

    最干的方法是什么?

    编写自定义授权属性:

    public class MyAuthorizeAttribute : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            var articleId = httpContext.Request["id"] as string;
            var article = SomeRepository.GetArticle(id);
            // You can also correlate the article with the currently 
            // connected user and see if it belongs to him, ...
            return article.IsPublic;
        }
    }
    

    然后用这个自定义属性装饰你的动作。

    【讨论】:

    猜你喜欢
    • 2013-05-18
    • 1970-01-01
    • 1970-01-01
    • 2015-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-29
    • 1970-01-01
    相关资源
    最近更新 更多