asp.net mvc – asp.net mvc decorate [Authorize()]与多个枚举
发布时间:2020-05-23 07:37:25 所属栏目: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-mvc – mvc创建我自己的html帮助器,如何访问httpco
- 在F#中开发ASP.NET和ASP.NET MVC应用程序的缺点?
- asp.net-mvc-3 – EF 4.1上的MvcMiniProfiler代码优先项目不
- asp.net – 如何忽略正则表达式的情况?
- asp.net-mvc – 刷新IdentityServer4客户端中的访问令牌
- asp.net-mvc – MVC4 Razor – @ Html.DisplayFor没有绑定到
- asp.net – .NET Web API 2 OWIN承载令牌认证
- asp.net – ApplicationInsight导致网站在启动时挂起
- ASP.NET等价的服务器端包括
- 析构函数何时在ASP.NET中调用C#类?
推荐文章
站长推荐
- ASP.NET C#,需要按两次按钮才能发生一些事情
- asp.net-mvc – asp.net mvc针对不同操作的不同验
- azure – 错误System.BadImageFormatException服
- iis – ASP.NET网站文件被黑了……怎么样?
- asp.net-mvc-3 – 具有确认对话框的MVC3 Actionl
- asp.net-mvc – 在ASP.NET MVC 3中路由静态文件,
- asp.net – 为不同项目中的所有Web应用程序网页添
- asp.net – SharePoint文件大小限制
- asp.net-core – 虚拟目录中的IIS站点Swagger UI
- asp.net-mvc – 一种在MVC环境中处理返回URL的智
热点阅读
