asp.net mvc – asp.net mvc decorate [Authorize()]与多个枚举
发布时间:2020-12-15 19:05:31 所属栏目:asp.Net 来源:网络整理
导读:我有一个控制器,我想要两个角色能够访问它。 1-admin或2 – 主持人 我知道你可以做[授权(角色=“管理员,版主”)],但我有我的角色在枚举。用枚举我只能授权一个角色。我不知道如何授权两个。 我试过像[Authorize(Roles = MyEnum.Admin,MyEnum.Moderator)]
|
我有一个控制器,我想要两个角色能够访问它。 1-admin或2 – 主持人
我知道你可以做[授权(角色=“管理员,版主”)],但我有我的角色在枚举。用枚举我只能授权一个角色。我不知道如何授权两个。 我试过像[Authorize(Roles = MyEnum.Admin,MyEnum.Moderator)]但是不会编译。 有人曾经建议: [Authorize(Roles=MyEnum.Admin)]
[Authorize(MyEnum.Moderator)]
public ActionResult myAction()
{
}
但它不工作作为OR。我认为在这种情况下,用户必须是BOTH角色的一部分。我可以忽略一些语法吗?或者是这种情况下,我必须滚动我自己的自定义授权? 解决方法
尝试使用位OR运算符:
[Authorize(Roles= MyEnum.Admin | MyEnum.Moderator)]
public ActionResult myAction()
{
}
如果这不工作,你可以自己滚。我目前只是在我的项目。这是我做的: public class AuthWhereRole : AuthorizeAttribute
{
/// <summary>
/// Add the allowed roles to this property.
/// </summary>
public UserRole Is;
/// <summary>
/// Checks to see if the user is authenticated and has the
/// correct role to access a particular view.
/// </summary>
/// <param name="httpContext"></param>
/// <returns></returns>
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (httpContext == null)
throw new ArgumentNullException("httpContext");
// Make sure the user is authenticated.
if (!httpContext.User.Identity.IsAuthenticated)
return false;
UserRole role = someUser.Role; // Load the user's role here
// Perform a bitwise operation to see if the user's role
// is in the passed in role values.
if (Is != 0 && ((Is & role) != role))
return false;
return true;
}
}
// Example Use
[AuthWhereRole(Is=MyEnum.Admin|MyEnum.Newbie)]
public ActionResult Test() {}
此外,请确保为您的枚举添加一个flags属性,并确保它们都从1开始计算。喜欢这个: [Flags]
public enum Roles
{
Admin = 1,Moderator = 1 << 1,Newbie = 1 << 2
etc...
}
左位移位给出值1,2,4,8,16等等。 嗯,我希望这有一点帮助。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- asp.net – 检查ValidationGroup是否从代码隐藏有效
- ASP.NET Core 认证与授权[5]:初识授权
- 身份验证 – 在达到会话和身份验证票证超时值之前,用户被迫
- asp.net – 如何增加url的最大长度?
- asp.net-mvc – 如何使用Razor ASp.NET MVC连接HTML元素的i
- asp.net-core – 在ASP.net Core中使用BeginCollectionItem
- asp.net – URL重写从/default.aspx到/
- asp.net-mvc – ASP.NET MVC2母版页 – 服务器端脚本无法渲
- asp.net – 对绑定到自定义通用对象列表的GridView进行排序
- ASP.Net MVC Script Bundle导致404
推荐文章
站长推荐
热点阅读
