MVC一次在控制器中授权属性

时间:2018-07-05 14:41:54

标签: asp.net-mvc

这是CustomAuthorizeAttribute类的内容:

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
         return (CurrentUser.IsInRole(MasterRole, ChildRole)) ? true : false;
    }
}

还有我的控制器:

[CustomAuthorize(MasterRole="Master")]
public class HomeController : Controller
{
...
    [CustomAuthorize(ChildRole = "Child")]
    public ActionResult Slider()
    {
        return View();
    }
...
}

在这种用法中,CustomAuthorizeAttribute类ChildRole的名称为“ Child”可以,但是MasterRole为空。

如何仅在控制器中一次定义“ MasterRole”,或者它可能吗?

我的意思是,它的工作方式如下语法,但我不想为以下每个动作定义MasterRole:

    [CustomAuthorize(MasterRole = "Master", ChildRole = "Child")]
    public ActionResult Slider()
    {
        return View();
    }

1 个答案:

答案 0 :(得分:0)

请参见在控制器上评估授权属性,然后再执行操作,您可能会稍微滥用授权系统。您可以在上下文中设置主角色,然后在操作的authorize属性中对其进行检索。

添加两个新属性,如下所示:

public class SetMasterRoleAttribute : AuthorizeAttribute
{
    public string MasterRole;

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        httpContext.Items.Add("MasterRole", MasterRole);
        return true;
    }
}

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    public string ChildRole;
    public string MasterRole;

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (string.IsNullOrEmpty(MasterRole))
        {
            MasterRole = httpContext.Items["MasterRole"] as string;
        }

        return (CurrentUser.IsInRole(MasterRole, ChildRole)) ? true : false;
    }
}

然后设置您的控制器和类似的动作:

[SetMasterRole(MasterRole = "Master")]
public class HomeController : Controller
{
    [CustomAuthorize(ChildRole = "Child")]
    public ActionResult Index()
    {
        return View();
    }
}