利用Attribute标记方法的调用权限
  TEZNKK3IfmPf 2024年08月09日 27 0

假设我们有这么一个标记来说明操作的权限:

    /// <summary>
    /// 声明权限的标记
    /// </summary>
    [AttributeUsage(AttributeTargets.Method)]
    public class PermissonAttribute : Attribute
    {
        public string Role { get; set; }

        public PermissonAttribute(string role)
        {
            this.Role = role;
        }

        public PermissonAttribute()
        {
        }
    }

有一个操作类应用了该标记:
    /// <summary>
    /// 文件操作类
    /// </summary>
    public class FileOperations
    {
        /// <summary>
        /// 任何人都可以调用Read
        /// </summary>
        [Permisson("Anyone")]
        public void Read()
        {
        }

        /// <summary>
        /// 只有文件所有者才能Write
        /// </summary>
        [Permisson("Owner")]
        public void Write()
        {
        }
    } 

然后我们写一个工具类来检查操作权限
/// <summary>
    /// 调用操作的工具类
    /// </summary>
    public static class OperationInvoker
    {
        public static void Invoke(object target, string role, string operationName, object[] parameters)
        {
            var targetType = target.GetType();
            var methodInfo = targetType.GetMethod(operationName);

            if (methodInfo.IsDefined(typeof(PermissonAttribute), false))
            {
                // 读取出所有权限相关的标记
                var permissons = methodInfo
                    .GetCustomAttributes(typeof(PermissonAttribute), false)
                    .OfType<PermissonAttribute>();
                // 如果其中有满足的权限
                if (permissons.Any(p => p.Role == role))
                {
                    methodInfo.Invoke(target, parameters);
                }
                else
                {
                    throw new Exception(string.Format("角色{0}没有访问操作{1}的权限!", role, operationName));
                }
            }
        }
    }

最后,在使用的时候:

var role = "Anyone";
var opertion = new FileOperations();
// 可以正常调用Read
OperationInvoker.Invoke(operation,role, "Read", null);
// 但是不能调用Write
OperationInvoker.Invoke(operation,role, "Write", null);
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2024年08月09日 0

暂无评论

推荐阅读
  TEZNKK3IfmPf   2024年05月31日   73   0   0 java权限
  TEZNKK3IfmPf   2023年11月14日   52   0   0 权限
  TEZNKK3IfmPf   2023年11月14日   39   0   0 权限数据库
  TEZNKK3IfmPf   2023年11月14日   58   0   0 权限mysql
  TEZNKK3IfmPf   2023年11月14日   38   0   0 权限shiro
  TEZNKK3IfmPf   2024年05月17日   73   0   0 权限dremio
TEZNKK3IfmPf