c# - 如果角色包含空格,如何编写 AuthorizeAttribute

标签 c# asp.net-mvc-3 authorization

我正在使用 MVC3/4。但这只是授权中的一般问题。

我有一个角色在数据库中名为“Trip Leader”,其中包含一个空格。

我尝试了 [Authorize(Roles="'Trip Leader', Administrator")] 但没有成功。谁能帮忙?

最佳答案

创建您自己的属性并派生自 AuthorizeAttribute。然后重写 AuthorizeCore 方法并通过对包含空格的角色进行验证来实现您自己的逻辑。

一个例子可能是这样的:

    public class CustomAuthAttribute : AuthorizeAttribute
    {
       private readonly IUserRoleService _userRoleService;
       private string[] _allowedRoles;
    
       public CustomAuthAttribute(params string[] roles)
       {
          _userRoleService = new UserRoleService();
          _allowedRoles = roles;
       }
       protected override bool AuthorizeCore(HttpContextBase httpContext)
       {
        //something like this.
        var userName = httpContext.User.Identity.Name;
        var userRoles = _userRoleService .GetUserRoles(userName); // return list of strings
        return _allowedRoles.Any(x => userRoles.Contains(x));
       }
   }

用法

[CustomAuth("role withspace","admin")]
public ActionResult Index()
{
}

关于c# - 如果角色包含空格,如何编写 AuthorizeAttribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10954907/

相关文章:

c# - 使用远程共享软件进行演示时 WPF 应用程序缓慢无响应

c# - 无法从 ASP.NET Core 2.1 Controller 获取 IdentityUser 数据

asp.net-mvc-3 - ASP.NET Web API - NTLM 身份验证和 HTTPS

asp.net-mvc - 使用 DisplayAttribute 和自定义资源提供程序进行 ASP.NET MVC 3 本地化

asp.net-mvc - 未授权用户时重定向到AccessDenied页面

c# - 阈值计算的优化

c# - WPF OpenFileDialog 在 c# 中使用 MVVM (Model-View-ViewModel)

jquery - 使用 jQuery 独立 Web 应用程序与服务器端演示框架

node.js - 表达限制资源属于特定用户的优雅方式

c# - 在 ASP.NET MVC 中重定向未经授权的 Controller