现在我像这样装饰一个方法,以允许“成员”访问我的控制器动作

[Authorize(Roles="members")]

如何允许多个角色?例如,下面的不工作,但它显示了我正在尝试做什么(允许“成员”和“管理员”访问):

[Authorize(Roles="members", "admin")] 

当前回答

另一个清晰的解决方案是使用常量来保持约定,并添加多个[Authorize]属性。看看这个:

public static class RolesConvention
{
    public const string Administrator = "Administrator";
    public const string Guest = "Guest";
}

然后在控制器中:

[Authorize(Roles = RolesConvention.Administrator )]
[Authorize(Roles = RolesConvention.Guest)]
[Produces("application/json")]
[Route("api/[controller]")]
public class MyController : Controller

其他回答

Intent promptInstall = new Intent(android.content.Intent.ACTION_VIEW);
promptInstall.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
promptInstall.setDataAndType(Uri.parse("http://10.0.2.2:8081/MyAPPStore/apk/Teflouki.apk"), "application/vnd.android.package-archive" );

startActivity(promptInstall);

使用AspNetCore 2。X,你必须走不同的路:

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class AuthorizeRoleAttribute : AuthorizeAttribute
{
    public AuthorizeRoleAttribute(params YourEnum[] roles)
    {
        Policy = string.Join(",", roles.Select(r => r.GetDescription()));
    }
}

就像这样使用它:

[Authorize(YourEnum.Role1, YourEnum.Role2)]

另一种选择是使用一个单独的授权过滤器,但删除内部报价。

[Authorize(Roles="members,admin")]

如果您发现自己经常应用这两个角色,您可以将它们包装在自己的Authorize中。这实际上是公认答案的延伸。

using System.Web.Mvc;

public class AuthorizeAdminOrMember : AuthorizeAttribute
{
    public AuthorizeAdminOrMember()
    {
        Roles = "members, admin";
    }
}

然后将新的授权应用到Action。我觉得这样看起来更干净,也更容易读。

public class MyController : Controller
{
    [AuthorizeAdminOrMember]
    public ActionResult MyAction()
    {
        return null;
    }
}

另一个清晰的解决方案是使用常量来保持约定,并添加多个[Authorize]属性。看看这个:

public static class RolesConvention
{
    public const string Administrator = "Administrator";
    public const string Guest = "Guest";
}

然后在控制器中:

[Authorize(Roles = RolesConvention.Administrator )]
[Authorize(Roles = RolesConvention.Guest)]
[Produces("application/json")]
[Route("api/[controller]")]
public class MyController : Controller