ASP.Net MVC:能否AuthorizeAttribute被重写? [英] ASP.Net MVC: Can the AuthorizeAttribute be overriden?

查看:151
本文介绍了ASP.Net MVC:能否AuthorizeAttribute被重写?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在的项目是使用ASP.Net MVC其中我加入身份验证建立了一个内部​​的Web应用程序。我有一个pre-内置的HttpModule它与适当的角色创建的IPrincipal。如果用户没有通过验证,我得到一个用户对象的角色公共

My current project is an internal web application built using ASP.Net MVC which I am adding authentication to. I have a pre-built HTTPModule which creates a IPrincipal with the appropriate roles. If the user isn't authenticated I get a user object with the role "Public"

由于这是一个内部应用程序的大部分网页都是私有的,只能查看到角色管理。因为我有一个基本的控制器我可以做到这一点:

As this is an internal application most of the pages are private and only viewable to the role "Admin". As I have a base controller I can do this:

[Authorize(Roles="Admin")]
public abstract class MyControllerBase : Controller
{
    ...
}

我有一个问题,但因为有些动作是在观看一个公共网站,如果我他们的属性,像这样:

I have a problem though as some of the actions are viewable on a public website and if I attribute them like so:

[Authorize(Roles="Public")]
public class LoginController : MyController
{
    public ActionResult Index()
    {

    }
}

的页面加载失败作为用户不被认证。这似乎公众对角色的继承类被忽略。有谁知道,如果角色可以由继承类中重写?

The page fails to load as the user isn't authenticated. It would seem the Role of "Public is being ignored on the inherited class. Does anyone know if the roles can be overridden by inherited classes?

我也试图避免归于所有控制器与角色=管理员

I am also trying to avoid attributing all the controllers with Roles="Admin"

谢谢,基思。

推荐答案

那么在最后,我认为我的回答是这个问题。相反,把授权属性我基地控制器上的我已经得出了新的AdminBaseController。

Well in the end I think my answer was in the question. Instead of putting the Authorize attribute on my base controller I have derived a new AdminBaseController.

[HandleError]
public abstract class MyControllerBase : Controller
{
    ...
}

[Authorize(Roles="Admin")]
public abstract class AdminControllerBase : MyControllerBase
{
    ....
}

现在需要身份验证可以从AdminControllerBase得到,而我的公共控制器可以由MyControllerBase获得任何控制器。 OO救援。

Now any controllers that require authentication can derive from AdminControllerBase while my public controllers can derive from MyControllerBase. OO to the rescue.

这篇关于ASP.Net MVC:能否AuthorizeAttribute被重写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆