public void Load() { this.dispatcher = new Dictionary <string, IHttpHandler>(); this.handlersMapping = new Dictionary <MethodInfo, IHttpHandler>(); this.getHandlers = new Dictionary <string, MethodInfo>(); this.postHandlers = new Dictionary <string, MethodInfo>(); HashSet <Type> types = Game.EventSystem.GetTypes(typeof(HttpHandlerAttribute)); foreach (Type type in types) { object[] attrs = type.GetCustomAttributes(typeof(HttpHandlerAttribute), false); if (attrs.Length == 0) { continue; } HttpHandlerAttribute httpHandlerAttribute = (HttpHandlerAttribute)attrs[0]; object obj = Activator.CreateInstance(type); IHttpHandler ihttpHandler = obj as IHttpHandler; if (ihttpHandler == null) { throw new Exception($"HttpHandler handler not inherit IHttpHandler class: {obj.GetType().FullName}"); } this.dispatcher.Add(httpHandlerAttribute.Path, ihttpHandler); LoadMethod(type, httpHandlerAttribute, ihttpHandler); } }
public void LoadMethod(Type type, HttpHandlerAttribute httpHandlerAttribute, IHttpHandler httpHandler) { // 扫描这个类里面的方法 MethodInfo[] methodInfos = type.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.InvokeMethod | BindingFlags.Instance); foreach (MethodInfo method in methodInfos) { object[] getAttrs = method.GetCustomAttributes(typeof(GetAttribute), false); if (getAttrs.Length != 0) { GetAttribute get = (GetAttribute)getAttrs[0]; string path = method.Name; if (!string.IsNullOrEmpty(get.Path)) { path = get.Path; } getHandlers.Add(httpHandlerAttribute.Path + path, method); //Log.Debug($"add handler[{httpHandler}.{method.Name}] path {httpHandlerAttribute.Path + path}"); } object[] postAttrs = method.GetCustomAttributes(typeof(PostAttribute), false); if (postAttrs.Length != 0) { // Post处理方法 PostAttribute post = (PostAttribute)postAttrs[0]; string path = method.Name; if (!string.IsNullOrEmpty(post.Path)) { path = post.Path; } postHandlers.Add(httpHandlerAttribute.Path + path, method); //Log.Debug($"add handler[{httpHandler}.{method.Name}] path {httpHandlerAttribute.Path + path}"); } if (getAttrs.Length == 0 && postAttrs.Length == 0) { continue; } handlersMapping.Add(method, httpHandler); } }