开发者

Controller requiring authorization only on specific parameters

I have a controller which loads an article and shows it. The article has a property that shows if it is priva开发者_如何学JAVAte or public.

If the article is private, I would like the user to log in before showing the article.

I cant just simply put an [Authorize] attribute on the action since if the article is public it shouldn't require authorization to show it.

What would be the most dry way to do this?

I would like to depend on the built in functionality of the default authorization model (I wouldn't want to write redirects and passing parameters manually if I don't need to)


What would be the most dry way to do this?

Write a custom authorize attribute:

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;
    }
}

and then decorate your action with this custom attribute.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜