如何写AuthorizeAttribute如果一个角色包含空格 [英] How to write AuthorizeAttribute if a role contains space

查看:144
本文介绍了如何写AuthorizeAttribute如果一个角色包含空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用MVC3 / 4。但它只是在授权一个一般性的问题。

I am using MVC3/4. But it is just a general question in authorization.

我有被命名为领袖之旅中的数据库,其中包含空格的作用。

One of the role I have is named "Trip Leader" in the database, which contains a space.

我试过 [授权(角色=旅行领袖,管理员)] ,但未能奏效。谁能帮助?

I tried [Authorize(Roles="'Trip Leader', Administrator")] but it failed to work. Can anyone help?

推荐答案

创建自己的属性,并从AuthorizeAttribute派生。然后重写AuthorizeCore方法,并与包含空格的作用验证实现你自己的逻辑。

Create your own attribute and derive from AuthorizeAttribute. Then override the AuthorizeCore method and implement your own logic with validation on a role that contains a space.

一个例子可能是这样的:

An example could be something like this:

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()
{
}

这篇关于如何写AuthorizeAttribute如果一个角色包含空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆