• Aop之使用Castle动态代理实现对方法的拦截


    using System;
    using System.Linq;
    using Castle.DynamicProxy;
    
    namespace AopTest
    {
        class AopTest
        {
            static public void Test()
            {
                var proxyGenerator = new ProxyGenerator();
                IUserService user = proxyGenerator.CreateClassProxy<UserService>(new UserRigthCheckProxy());
                user.GetUser("admin");
                user.GetUser("guest");
                user.UpdateUser("admin");
                user.UpdateUser("guest");
            }
        }
    
        public interface IUserService
        {
            void GetUser(string userId);
            void UpdateUser(string userId);
        }
    
        public class UserService : IUserService
        {
            public virtual void GetUser(string userId)
            {
                Console.WriteLine(userId + ",Welcome!");
            }
            public virtual void UpdateUser(string userId)
            {
                Console.WriteLine(userId + ",Updated!");
            }
        }
    
        public class UserRigthCheckProxy : IInterceptor
        {
            private static readonly string[] RightOperations = new string[] { "UpdateUser" };
            public void Intercept(IInvocation invocation)
            {
                if (invocation.Arguments.Length > 0 && invocation.Arguments[0] is string)
                {
                    if (RightOperations.Contains(invocation.Method.Name))
                    {
                        var userId = (string) invocation.Arguments[0];
                        if (userId == "admin")
                        {
                            Console.WriteLine("有权限操作 ");
                            invocation.Proceed();
                        }
                        else
                        {
                            Console.WriteLine("{0},您没有权限操作", userId);
                        }
                    }
                    else
                    {
                        Console.WriteLine("有权限操作 ");
                        invocation.Proceed();
                    }
                }
                else
                {
                    invocation.Proceed();
                }
            }
        }
    }
  • 相关阅读:
    Java web实验 Login.jsp session属性设置和获取
    Java web实验Outapp.jsp
    Java web实验Accept.jsp
    Java web实验Register.jsp
    Java web实验 Redirect.jsp
    requestAPP1.jps
    out对象
    Request获取请求路径方法介绍
    数据流图
    web应用程序的请求和响应
  • 原文地址:https://www.cnblogs.com/zhshlimi/p/8073880.html
Copyright © 2020-2023  润新知