示例#1
0
        public void SetAction(ActionHandler handler)
        {
            var item = Settings.Find(i => i.Url.ToLower() == handler.Url.ToLower());

            if (item != null)
            {
                item.SetTo(handler);
            }
        }
        public ActionResult ExecuteWithWS(HttpRequest request, HttpApiServer server, JToken token)
        {
            ActionResult result = new ActionResult();
            JToken       url    = token["url"];

            WebSockets.DataFrame dataFrame = server.CreateDataFrame(result);
            if (url == null)
            {
                result.Code  = 403;
                result.Error = "not fupport url info notfound!";
                return(result);
            }
            result.Url = url.Value <string>();
            string        baseurl = HttpParse.CharToLower(result.Url);
            ActionHandler handler = GetAction(baseurl);

            if (handler == null)
            {
                server.BaseServer.Log(EventArgs.LogType.Warring, request.Session, baseurl + " not found");
                result.Code  = 404;
                result.Error = "url " + baseurl + " notfound!";
                request.Session.Send(dataFrame);
            }
            else
            {
                try
                {
                    JToken data = token["params"];
                    if (data == null)
                    {
                        data = (JToken)Newtonsoft.Json.JsonConvert.DeserializeObject("{}");
                    }
                    WebsocketJsonDataContext dc      = new WebsocketJsonDataContext(server, request, data);
                    ActionContext            context = new ActionContext(handler, dc);
                    context.Execute();
                    if (!dc.AsyncResult)
                    {
                        result.Data = context.Result;
                        request.Session.Send(dataFrame);
                    }
                }
                catch (Exception e_)
                {
                    server.BaseServer.Log(EventArgs.LogType.Error, request.Session, "{0} inner error {1}@{2}", request.Url, e_.Message, e_.StackTrace);
                    result.Code  = 500;
                    result.Error = e_.Message;
                    if (server.ServerConfig.OutputStackTrace)
                    {
                        result.StackTrace = e_.StackTrace;
                    }
                    request.Session.Send(dataFrame);
                }
            }
            return(result);
        }
示例#3
0
 internal bool OnActionExecuting(IHttpContext context, ActionHandler handler)
 {
     if (ActionExecuting != null)
     {
         EventActionExecutingArgs e = new EventActionExecutingArgs();
         e.HttpContext = context;
         e.Handler     = handler;
         ActionExecuting(this, e);
         return(!e.Cancel);
     }
     return(true);
 }
示例#4
0
 public ActionInfo(ActionHandler handler)
 {
     Url    = handler.Url;
     MaxRps = handler.MaxRPS;
     if (handler.ThreadQueue != null)
     {
         ThreadInfo = ThreadInfo.GetThreadInfo(handler.ThreadQueue);
     }
     else
     {
         ThreadInfo = new ThreadInfo();
     }
 }
示例#5
0
 public static ThreadInfo GetThreadInfo(ActionHandler handler)
 {
     if (handler.ThreadQueue != null)
     {
         return(GetThreadInfo(handler.ThreadQueue));
     }
     else
     {
         return new ThreadInfo {
                    Type = "None"
         }
     };
 }
示例#6
0
 public void SetTo(ActionHandler handler)
 {
     handler.MaxRPS = MaxRps;
     if (ThreadInfo != null)
     {
         if (ThreadInfo.Type == ThreadQueueType.None.ToString())
         {
             handler.ThreadQueue = null;
         }
         else
         {
             handler.ThreadQueue = ThreadInfo?.GetThreadQueue();
         }
     }
 }
        public void Execute(HttpRequest request, HttpResponse response, HttpApiServer server)
        {
            ActionHandler handler = GetAction(request.BaseUrl);

            if (handler == null)
            {
                if (server.EnableLog(EventArgs.LogType.Warring))
                {
                    server.BaseServer.Log(EventArgs.LogType.Warring, request.Session, "{0} execute {1} action  not found", request.ClientIPAddress, request.Url);
                }
                if (!server.OnHttpRequesNotfound(request, response).Cancel)
                {
                    NotFoundResult notFoundResult = new NotFoundResult("{0} action not found", request.Url);
                    response.Result(notFoundResult);
                }
            }
            else
            {
                try
                {
                    HttpContext pc        = new HttpContext(server, request, response);
                    long        startTime = server.BaseServer.GetRunTime();
                    pc.ActionUrl = request.BaseUrl;
                    ActionContext context = new ActionContext(handler, pc);
                    context.Execute();
                    if (!response.AsyncResult)
                    {
                        object result = context.Result;
                        response.Result(result);
                        if (server.EnableLog(EventArgs.LogType.Info))
                        {
                            server.BaseServer.Log(EventArgs.LogType.Info, request.Session, "{0} http execute {1} action use time:{2}ms", request.ClientIPAddress,
                                                  request.BaseUrl, server.BaseServer.GetRunTime() - startTime);
                        }
                    }
                }
                catch (Exception e_)
                {
                    InnerErrorResult result = new InnerErrorResult(e_, server.ServerConfig.OutputStackTrace);
                    response.Result(result);

                    if (server.EnableLog(EventArgs.LogType.Error))
                    {
                        response.Session.Server.Log(EventArgs.LogType.Error, response.Session, "{0} execute {1} action inner error {2}@{3}", request.ClientIPAddress, request.Url, e_.Message, e_.StackTrace);
                    }
                }
            }
        }
 public void Remove(ActionHandler handler)
 {
     if (handler != null)
     {
         lock (mMethods)
         {
             if (mMethods.ContainsKey(handler.Url))
             {
                 mMethods.Remove(handler.Url);
                 if (Server.EnableLog(EventArgs.LogType.Info))
                 {
                     Server.Log(EventArgs.LogType.Info, $"remove {handler.Url} action handler");
                 }
             }
         }
     }
 }
示例#9
0
 internal ActionContext(ActionHandler handler, IHttpContext context, ActionHandlerFactory actionHandlerFactory)
 {
     Handler              = handler;
     mFilters             = handler.Filters;
     HttpContext          = context;
     ActionHandlerFactory = actionHandlerFactory;
     Parameters           = handler.GetParameters(context);
     Controller           = handler.Controller;
     if (!handler.SingleInstance)
     {
         Controller = actionHandlerFactory.GetController(handler.ControllerType);
         if (Controller == null)
         {
             Controller = this.Controller;
         }
     }
 }
示例#10
0
 internal ActionContext(ActionHandler handler, IHttpContext context, ActionHandlerFactory actionHandlerFactory)
 {
     Handler              = handler;
     mFilters             = handler.Filters;
     HttpContext          = context;
     ActionHandlerFactory = actionHandlerFactory;
     Parameters           = handler.GetParameters(context);
     Controller           = handler.Controller;
     if (handler.InstanceType != InstanceType.Single)
     {
         if (handler.InstanceType == InstanceType.Session)
         {
             var factory = SessionControllerFactory.GetFactory(context.Session);
             Controller = factory[handler.ControllerUID];
             if (Controller == null)
             {
                 Controller = actionHandlerFactory.GetController(handler.ControllerType, context);
                 if (Controller == null)
                 {
                     Controller = Activator.CreateInstance(handler.ControllerType);
                 }
                 factory[handler.ControllerUID] = Controller;
             }
         }
         else
         {
             Controller = actionHandlerFactory.GetController(handler.ControllerType, context);
             if (Controller == null)
             {
                 Controller = Activator.CreateInstance(handler.ControllerType);
             }
         }
     }
     if (Controller == null)
     {
         Controller = handler.Controller;
     }
 }
示例#11
0
        public void Execute(HttpRequest request, HttpResponse response, HttpApiServer server)
        {
            ActionHandler handler = GetAction(request.BaseUrl);

            if (handler == null)
            {
                if (server.EnableLog(EventArgs.LogType.Warring))
                {
                    server.BaseServer.Log(EventArgs.LogType.Warring, request.Session, "{0} execute {1} action  not found", request.ClientIPAddress, request.Url);
                }
                response.NotFound();
            }
            else
            {
                try
                {
                    HttpContext pc = new HttpContext(server, request, response);
                    pc.ActionUrl = request.BaseUrl;
                    ActionContext context = new ActionContext(handler, pc);
                    context.Execute();
                    if (!response.AsyncResult)
                    {
                        object result = context.Result;
                        response.Result(result);
                    }
                }
                catch (Exception e_)
                {
                    response.InnerError(e_, server.ServerConfig.OutputStackTrace);
                    if (server.EnableLog(EventArgs.LogType.Error))
                    {
                        response.Session.Server.Log(EventArgs.LogType.Error, response.Session, "{0} execute {1} action inner error {2}@{3}", request.ClientIPAddress, request.Url, e_.Message, e_.StackTrace);
                    }
                }
            }
        }
示例#12
0
        public void ExecuteWithWS(HttpRequest request, HttpApiServer server, JToken token)
        {
            ActionResult result = new ActionResult();
            JToken       url    = token["url"];

            WebSockets.DataFrame dataFrame = server.CreateDataFrame(result);
            if (url == null)
            {
                if (server.EnableLog(EventArgs.LogType.Warring))
                {
                    server.BaseServer.Log(EventArgs.LogType.Warring, null, $"Websocket {request.ID} {request.RemoteIPAddress} process error action url info notfound!");
                }
                result.Code  = 403;
                result.Error = "not support, url info notfound!";
                request.Session.Send(dataFrame);
                return;
            }
            result.Url = url.Value <string>();
            string baseurl = result.Url;

            if (server.Options.UrlIgnoreCase)
            {
                baseurl = HttpParse.CharToLower(result.Url);
            }
            if (baseurl[0] != '/')
            {
                baseurl = "/" + baseurl;
            }
            result.Url = baseurl;
            JToken data = token["params"];

            if (data == null)
            {
                data = (JToken)Newtonsoft.Json.JsonConvert.DeserializeObject("{}");
            }
            JToken requestid = data["_requestid"];

            if (requestid != null)
            {
                result.ID = requestid.Value <string>();
            }

            ActionHandler handler = GetAction(baseurl);

            if (handler == null)
            {
                if (server.EnableLog(EventArgs.LogType.Warring))
                {
                    server.BaseServer.Log(EventArgs.LogType.Warring, null, $"Websocket {request.ID} {request.RemoteIPAddress} ws execute {result.Url} notfound!");
                }
                result.Code  = 404;
                result.Error = "url " + baseurl + " notfound!";
                request.Session.Send(dataFrame);
            }
            else
            {
                try
                {
                    Data.DataContxt dataContxt = new Data.DataContxt();
                    DataContextBind.BindJson(dataContxt, data);
                    WebsocketJsonContext dc = new WebsocketJsonContext(server, request, dataContxt);
                    dc.ActionUrl = baseurl;
                    dc.RequestID = result.ID;
                    if (!Server.OnActionExecuting(dc))
                    {
                        return;
                    }
                    ActionContext         context               = new ActionContext(handler, dc, this);
                    long                  startTime             = server.BaseServer.GetRunTime();
                    WSActionResultHandler wSActionResultHandler = new WSActionResultHandler(dc, server, request, result, dataFrame, startTime);
                    if (!handler.HasValidation || handler.ValidateParamters(context.Parameters, out (Validations.ValidationBase, ParameterInfo)error))
                    {
                        context.Execute(wSActionResultHandler);
                    }
                    else
                    {
                        server.ValidationOutputHandler.Execute(dc, wSActionResultHandler, error.Item1, error.Item2);
                    }
                }
示例#13
0
        public ActionResult ExecuteWithWS(HttpRequest request, HttpApiServer server, JToken token)
        {
            ActionResult result = new ActionResult();
            JToken       url    = token["url"];

            WebSockets.DataFrame dataFrame = server.CreateDataFrame(result);
            if (url == null)
            {
                if (server.EnableLog(EventArgs.LogType.Warring))
                {
                    server.BaseServer.Log(EventArgs.LogType.Warring, request.Session, "websocket {0} not support, url info notfound!", request.ClientIPAddress);
                }
                result.Code  = 403;
                result.Error = "not support, url info notfound!";
                request.Session.Send(dataFrame);
                return(result);
            }
            result.Url = url.Value <string>();
            string baseurl = HttpParse.CharToLower(result.Url);

            if (baseurl[0] != '/')
            {
                baseurl = "/" + baseurl;
            }
            result.Url = baseurl;
            JToken data = token["params"];

            if (data == null)
            {
                data = (JToken)Newtonsoft.Json.JsonConvert.DeserializeObject("{}");
            }
            JToken requestid = data["_requestid"];

            if (requestid != null)
            {
                result.ID = requestid.Value <string>();
            }
            ActionHandler handler = GetAction(baseurl);

            if (handler == null)
            {
                if (server.EnableLog(EventArgs.LogType.Warring))
                {
                    server.BaseServer.Log(EventArgs.LogType.Warring, request.Session, "websocket {0} execute {1} notfound", request.ClientIPAddress, result.Url);
                }
                result.Code  = 404;
                result.Error = "url " + baseurl + " notfound!";
                request.Session.Send(dataFrame);
            }
            else
            {
                try
                {
                    WebsocketContext dc = new WebsocketContext(server, request, data);
                    dc.ActionUrl = baseurl;
                    dc.RequestID = result.ID;
                    ActionContext context = new ActionContext(handler, dc);
                    context.Execute();
                    if (!dc.AsyncResult)
                    {
                        if (context.Result is ActionResult)
                        {
                            result    = (ActionResult)context.Result;
                            result.ID = dc.RequestID;
                            if (result.Url == null)
                            {
                                result.Url = dc.ActionUrl;
                            }
                            dataFrame.Body = result;
                        }
                        else
                        {
                            result.Data = context.Result;
                        }
                        dataFrame.Send(request.Session);
                        //request.Session.Send(dataFrame);
                    }
                }
                catch (Exception e_)
                {
                    if (server.EnableLog(EventArgs.LogType.Error))
                    {
                        server.BaseServer.Log(EventArgs.LogType.Error, request.Session, "websocket {0} execute {1} inner error {2}@{3}", request.ClientIPAddress, request.Url, e_.Message, e_.StackTrace);
                    }
                    result.Code  = 500;
                    result.Error = e_.Message;
                    if (server.ServerConfig.OutputStackTrace)
                    {
                        result.StackTrace = e_.StackTrace;
                    }
                    dataFrame.Send(request.Session);
                    //request.Session.Send(dataFrame);
                }
            }
            return(result);
        }
示例#14
0
        public void Execute(HttpRequest request, HttpResponse response, HttpApiServer server)
        {
            ActionHandler handler = GetAction(request.BaseUrl);

            if (handler == null)
            {
                if (server.EnableLog(EventArgs.LogType.Warring))
                {
                    server.BaseServer.Log(EventArgs.LogType.Warring, request.Session, "{0} execute {1} action  not found", request.ClientIPAddress, request.Url);
                }
                if (!server.OnHttpRequesNotfound(request, response).Cancel)
                {
                    NotFoundResult notFoundResult = new NotFoundResult("{0} action not found", request.Url);
                    response.Result(notFoundResult);
                }
            }
            else
            {
                try
                {
                    if (request.Method != handler.Method)
                    {
                        if (server.EnableLog(EventArgs.LogType.Warring))
                        {
                            server.BaseServer.Log(EventArgs.LogType.Warring, request.Session, "{0} execute {1} action  {1} not support", request.ClientIPAddress, request.Url, request.Method);
                        }
                        NotSupportResult notSupportResult = new NotSupportResult("{0} action not support {1}", request.Url, request.Method);
                        response.Result(notSupportResult);
                        return;
                    }
                    if (!handler.NoConvert && handler.DataConvert == null)
                    {
                        handler.DataConvert = DataContextBind.GetConvertAttribute(request.ContentType);
                    }
                    if (!handler.NoConvert)
                    {
                        handler.DataConvert.Execute(request.Data, request);
                    }
                    HttpContext pc        = new HttpContext(server, request, response, request.Data);
                    long        startTime = server.BaseServer.GetRunTime();
                    pc.ActionUrl = request.BaseUrl;
                    ActionContext context = new ActionContext(handler, pc, this);
                    context.Execute();
                    if (!response.AsyncResult)
                    {
                        object result = context.Result;
                        response.Result(result);
                        if (server.EnableLog(EventArgs.LogType.Info))
                        {
                            server.BaseServer.Log(EventArgs.LogType.Info, request.Session, "{0} http execute {1} action use time:{2}ms", request.ClientIPAddress,
                                                  request.BaseUrl, server.BaseServer.GetRunTime() - startTime);
                        }
                    }
                }
                catch (Exception e_)
                {
                    InnerErrorResult result = new InnerErrorResult($"http execute {request.BaseUrl} action error ", e_, server.ServerConfig.OutputStackTrace);
                    response.Result(result);

                    if (server.EnableLog(EventArgs.LogType.Error))
                    {
                        response.Session.Server.Log(EventArgs.LogType.Error, response.Session, "{0} execute {1} action inner error {2}@{3}", request.ClientIPAddress, request.Url, e_.Message, e_.StackTrace);
                    }
                }
            }
        }
        private void Register(HttpConfig config, Type controllerType, object controller, string rooturl, HttpApiServer server)
        {
            if (string.IsNullOrEmpty(rooturl))
            {
                rooturl = "/";
            }
            else
            {
                if (rooturl[0] != '/')
                {
                    rooturl = "/" + rooturl;
                }
                if (rooturl[rooturl.Length - 1] != '/')
                {
                    rooturl += "/";
                }
            }
            List <FilterAttribute> filters = new List <FilterAttribute>();

            filters.AddRange(config.Filters);
            IEnumerable <FilterAttribute> fas = controllerType.GetCustomAttributes <FilterAttribute>(false);

            filters.AddRange(fas);
            IEnumerable <SkipFilterAttribute> skipfilters = controllerType.GetCustomAttributes <SkipFilterAttribute>(false);

            foreach (SkipFilterAttribute item in skipfilters)
            {
                RemoveFilter(filters, item.Types);
            }
            object obj = controller;

            if (obj is IController)
            {
                ((IController)obj).Init(server);
            }
            foreach (MethodInfo mi in controllerType.GetMethods(BindingFlags.Instance | BindingFlags.Public))
            {
                if (string.Compare("Equals", mi.Name, true) == 0 ||
                    string.Compare("GetHashCode", mi.Name, true) == 0 ||
                    string.Compare("GetType", mi.Name, true) == 0 ||
                    string.Compare("ToString", mi.Name, true) == 0)
                {
                    continue;
                }
                if (mi.GetCustomAttribute <NotActionAttribute>(false) != null)
                {
                    continue;
                }
                string        sourceUrl = rooturl + mi.Name;
                string        url       = sourceUrl.ToLower();
                ActionHandler handler   = GetAction(url);
                if (handler != null)
                {
                    server.Log(EventArgs.LogType.Error, "{0} already exists!duplicate definition {1}.{2}!", url, controllerType.Name,
                               mi.Name);
                    continue;
                }
                handler           = new ActionHandler(obj, mi);
                handler.SourceUrl = sourceUrl;
                handler.Filters.AddRange(filters);
                fas = mi.GetCustomAttributes <FilterAttribute>(false);
                handler.Filters.AddRange(fas);
                skipfilters = mi.GetCustomAttributes <SkipFilterAttribute>(false);
                foreach (SkipFilterAttribute item in skipfilters)
                {
                    RemoveFilter(handler.Filters, item.Types);
                }
                mMethods[url] = handler;
                server.Log(EventArgs.LogType.Info, "register {0}.{1} to {2}", controllerType.Name, mi.Name, url);
            }
        }
        public void Execute(HttpRequest request, HttpResponse response, HttpApiServer server)
        {
            ActionHandler handler = GetAction(request.BaseUrl);

            if (handler == null)
            {
                if (server.EnableLog(EventArgs.LogType.Warring))
                {
                    server.BaseServer.Log(EventArgs.LogType.Warring, request.Session, $"{request.RemoteIPAddress} {request.Method} {request.Url}  not found");
                }
                if (!server.OnHttpRequesNotfound(request, response).Cancel)
                {
                    NotFoundResult notFoundResult = new NotFoundResult($"{request.Method} {request.Url} not found");
                    response.Result(notFoundResult);
                }
            }
            else
            {
                try
                {
                    if (request.Method != handler.Method)
                    {
                        if (request.Method == HttpParse.OPTIONS_TAG && handler.OptionsAttribute != null)
                        {
                            if (server.EnableLog(EventArgs.LogType.Info))
                            {
                                server.BaseServer.Log(EventArgs.LogType.Info, request.Session, $"{request.RemoteIPAddress}{request.Method}{request.Url} request");
                            }
                            response.Result(handler.OptionsAttribute);
                        }
                        else
                        {
                            if (server.EnableLog(EventArgs.LogType.Warring))
                            {
                                server.BaseServer.Log(EventArgs.LogType.Warring, request.Session, $"{request.RemoteIPAddress}{request.Method} {request.Url} not support");
                            }
                            NotSupportResult notSupportResult = new NotSupportResult($"{request.Method}{request.Url} not support");
                            response.Result(notSupportResult);
                        }
                        return;
                    }
                    if (!handler.NoConvert && handler.DataConvert == null)
                    {
                        handler.DataConvert = DataContextBind.GetConvertAttribute(request.ContentType);
                    }
                    if (!handler.NoConvert)
                    {
                        handler.DataConvert.Execute(request.Data, request);
                    }
                    HttpContext pc        = new HttpContext(server, request, response, request.Data);
                    long        startTime = server.BaseServer.GetRunTime();
                    pc.ActionUrl = request.BaseUrl;
                    HttpActionResultHandler actionResult = new HttpActionResultHandler(Server, request, response, startTime);
                    ActionContext           context      = new ActionContext(handler, pc, this);
                    if (handler.OptionsAttribute != null)
                    {
                        handler.OptionsAttribute.SetResponse(request, response);
                    }
                    context.Execute(actionResult);
                }
                catch (Exception e_)
                {
                    handler.IncrementError();
                    if (server.EnableLog(EventArgs.LogType.Error))
                    {
                        server.Log(EventArgs.LogType.Error, $"{request.RemoteIPAddress} http {request.Method} { request.Url} inner error {e_.Message}@{e_.StackTrace}");
                    }
                    InnerErrorResult result = new InnerErrorResult($"http execute {request.BaseUrl} error ", e_, server.Options.OutputStackTrace);
                    response.Result(result);
                }
            }
        }
        private void Register(HttpOptions config, Type controllerType, object controller, string rooturl, HttpApiServer server, ControllerAttribute ca)
        {
            DataConvertAttribute controllerDataConvert      = controllerType.GetCustomAttribute <DataConvertAttribute>(false);
            OptionsAttribute     controllerOptionsAttribute = controllerType.GetCustomAttribute <OptionsAttribute>(false);

            if (string.IsNullOrEmpty(rooturl))
            {
                rooturl = "/";
            }
            else
            {
                if (rooturl[0] != '/')
                {
                    rooturl = "/" + rooturl;
                }
                if (rooturl[rooturl.Length - 1] != '/')
                {
                    rooturl += "/";
                }
            }
            RequestMaxRPS          control_maxRPS = controllerType.GetCustomAttribute <RequestMaxRPS>();
            List <FilterAttribute> filters        = new List <FilterAttribute>();

            filters.AddRange(config.Filters);
            IEnumerable <FilterAttribute> fas = controllerType.GetCustomAttributes <FilterAttribute>(false);

            filters.AddRange(fas);
            IEnumerable <SkipFilterAttribute> skipfilters = controllerType.GetCustomAttributes <SkipFilterAttribute>(false);

            foreach (SkipFilterAttribute item in skipfilters)
            {
                RemoveFilter(filters, item.Types);
            }
            object obj = controller;

            if (obj is IController)
            {
                string path = System.IO.Path.GetDirectoryName(controllerType.Assembly.Location) + System.IO.Path.DirectorySeparatorChar;
                ((IController)obj).Init(server, path);
                server.Log(EventArgs.LogType.Info, $"init {controllerType} controller path {path}");
            }
            foreach (MethodInfo mi in controllerType.GetMethods(BindingFlags.Instance | BindingFlags.Public))
            {
                if (string.Compare("Equals", mi.Name, true) == 0 ||
                    string.Compare("GetHashCode", mi.Name, true) == 0 ||
                    string.Compare("GetType", mi.Name, true) == 0 ||
                    string.Compare("ToString", mi.Name, true) == 0 || mi.Name.IndexOf("set_") >= 0 ||
                    mi.Name.IndexOf("get_") >= 0)
                {
                    continue;
                }
                if (mi.GetCustomAttribute <NotActionAttribute>(false) != null)
                {
                    continue;
                }
                bool          noconvert = false;
                RequestMaxRPS maxRPS    = mi.GetCustomAttribute <RequestMaxRPS>();
                if (maxRPS == null)
                {
                    maxRPS = control_maxRPS;
                }
                DataConvertAttribute actionConvert          = mi.GetCustomAttribute <DataConvertAttribute>();
                OptionsAttribute     methodOptionsAttribute = mi.GetCustomAttribute <OptionsAttribute>();
                if (mi.GetCustomAttribute <NoDataConvertAttribute>(false) != null)
                {
                    noconvert     = true;
                    actionConvert = null;
                }
                else
                {
                    if (actionConvert == null)
                    {
                        actionConvert = controllerDataConvert;
                    }
                }
                string       sourceUrl = rooturl + mi.Name;
                string       url       = sourceUrl;
                string       method    = HttpParse.GET_TAG;
                string       route     = null;
                GetAttribute get       = mi.GetCustomAttribute <GetAttribute>(false);
                if (get != null)
                {
                    method = HttpParse.GET_TAG;
                    route  = get.Route;
                }
                PostAttribute post = mi.GetCustomAttribute <PostAttribute>(false);
                if (post != null)
                {
                    method = HttpParse.POST_TAG;
                    route  = post.Route;
                }
                DelAttribute del = mi.GetCustomAttribute <DelAttribute>(false);
                if (del != null)
                {
                    method = HttpParse.DELETE_TAG;
                    route  = del.Route;
                }
                PutAttribute put = mi.GetCustomAttribute <PutAttribute>(false);
                if (put != null)
                {
                    method = HttpParse.PUT_TAG;
                    route  = put.Route;
                }

                if (server.Options.UrlIgnoreCase)
                {
                    url = sourceUrl.ToLower();
                }
                RouteTemplateAttribute ra = null;
                if (!string.IsNullOrEmpty(route))
                {
                    ra = new RouteTemplateAttribute(route);
                    string reurl = ra.Analysis(url);
                    if (reurl != null)
                    {
                        server.UrlRewrite.Add(reurl, url);
                    }
                }
                ActionHandler handler = GetAction(url);
                if (handler != null)
                {
                    server.Log(EventArgs.LogType.Warring, "{0} already exists!replaced with {1}.{2}!", url, controllerType.Name,
                               mi.Name);
                }

                handler = new ActionHandler(obj, mi);
                if (mi.ReturnType == typeof(Task) || mi.ReturnType.BaseType == typeof(Task))
                {
                    handler.Async = true;
                    PropertyInfo pi = mi.ReturnType.GetProperty("Result", BindingFlags.Public | BindingFlags.Instance);
                    if (pi != null)
                    {
                        handler.PropertyHandler = new PropertyHandler(pi);
                    }
                }
                handler.Path = rooturl;
                if (methodOptionsAttribute == null)
                {
                    handler.OptionsAttribute = controllerOptionsAttribute;
                }
                else
                {
                    handler.OptionsAttribute = methodOptionsAttribute;
                }
                handler.NoConvert      = noconvert;
                handler.SingleInstance = ca.SingleInstance;
                handler.DataConvert    = actionConvert;
                handler.Route          = ra;
                handler.Method         = method;
                handler.SourceUrl      = sourceUrl;
                handler.Filters.AddRange(filters);
                fas = mi.GetCustomAttributes <FilterAttribute>(false);
                handler.Filters.AddRange(fas);
                handler.Url = url;
                if (maxRPS != null)
                {
                    handler.MaxRPS = maxRPS.Value;
                }
                int rpsSetting = server.Options.GetActionMaxrps(handler.SourceUrl);
                if (rpsSetting > 0)
                {
                    handler.MaxRPS = rpsSetting;
                }
                skipfilters = mi.GetCustomAttributes <SkipFilterAttribute>(false);
                foreach (SkipFilterAttribute item in skipfilters)
                {
                    RemoveFilter(handler.Filters, item.Types);
                }
                AddHandlers(url, handler);
                server.Log(EventArgs.LogType.Info, $"register { controllerType.Name}.{mi.Name} to [{handler.Method}:{url}]");
            }
        }
示例#18
0
 internal ActionContext(ActionHandler handler, IHttpContext context)
 {
     mHandler    = handler;
     mFilters    = handler.Filters;
     HttpContext = context;
 }
        public ActionResult ExecuteWithWS(HttpRequest request, HttpApiServer server, JToken token)
        {
            ActionResult result = new ActionResult();
            JToken       url    = token["url"];

            WebSockets.DataFrame dataFrame = server.CreateDataFrame(result);
            if (url == null)
            {
                if (server.EnableLog(EventArgs.LogType.Warring))
                {
                    server.BaseServer.Log(EventArgs.LogType.Warring, request.Session, "{0} ws not support, url info notfound!", request.RemoteIPAddress);
                }
                result.Code  = 403;
                result.Error = "not support, url info notfound!";
                request.Session.Send(dataFrame);
                return(result);
            }
            result.Url = url.Value <string>();
            string baseurl = result.Url;

            if (server.Options.UrlIgnoreCase)
            {
                baseurl = HttpParse.CharToLower(result.Url);
            }
            if (baseurl[0] != '/')
            {
                baseurl = "/" + baseurl;
            }
            result.Url = baseurl;
            JToken data = token["params"];

            if (data == null)
            {
                data = (JToken)Newtonsoft.Json.JsonConvert.DeserializeObject("{}");
            }
            JToken requestid = data["_requestid"];

            if (requestid != null)
            {
                result.ID = requestid.Value <string>();
            }

            ActionHandler handler = GetAction(baseurl);

            if (handler == null)
            {
                if (server.EnableLog(EventArgs.LogType.Warring))
                {
                    server.BaseServer.Log(EventArgs.LogType.Warring, request.Session, "{0} ws execute {1} notfound", request.RemoteIPAddress, result.Url);
                }
                result.Code  = 404;
                result.Error = "url " + baseurl + " notfound!";
                request.Session.Send(dataFrame);
            }
            else
            {
                try
                {
                    Data.DataContxt dataContxt = new Data.DataContxt();
                    DataContextBind.BindJson(dataContxt, data);
                    WebsocketJsonContext dc = new WebsocketJsonContext(server, request, dataContxt);
                    dc.ActionUrl = baseurl;
                    dc.RequestID = result.ID;
                    ActionContext         context               = new ActionContext(handler, dc, this);
                    long                  startTime             = server.BaseServer.GetRunTime();
                    WSActionResultHandler wSActionResultHandler = new WSActionResultHandler(dc, server, request, result, dataFrame, startTime);
                    context.Execute(wSActionResultHandler);
                }
                catch (Exception e_)
                {
                    handler.IncrementError();
                    if (server.EnableLog(EventArgs.LogType.Error))
                    {
                        server.BaseServer.Log(EventArgs.LogType.Error, request.Session, "{0} ws execute {1} inner error {2}@{3}", request.RemoteIPAddress, result.Url, e_.Message, e_.StackTrace);
                    }
                    result.Code  = 500;
                    result.Error = e_.Message;
                    if (server.Options.OutputStackTrace)
                    {
                        result.StackTrace = e_.StackTrace;
                    }
                    dataFrame.Send(request.Session);
                }
            }
            return(result);
        }
示例#20
0
        private void Register(HttpConfig config, Type controllerType, object controller, string rooturl, HttpApiServer server)
        {
            DataConvertAttribute controllerDataConvert = controllerType.GetCustomAttribute <DataConvertAttribute>(false);

            if (string.IsNullOrEmpty(rooturl))
            {
                rooturl = "/";
            }
            else
            {
                if (rooturl[0] != '/')
                {
                    rooturl = "/" + rooturl;
                }
                if (rooturl[rooturl.Length - 1] != '/')
                {
                    rooturl += "/";
                }
            }
            List <FilterAttribute> filters = new List <FilterAttribute>();

            filters.AddRange(config.Filters);
            IEnumerable <FilterAttribute> fas = controllerType.GetCustomAttributes <FilterAttribute>(false);

            filters.AddRange(fas);
            IEnumerable <SkipFilterAttribute> skipfilters = controllerType.GetCustomAttributes <SkipFilterAttribute>(false);

            foreach (SkipFilterAttribute item in skipfilters)
            {
                RemoveFilter(filters, item.Types);
            }
            object obj = controller;

            if (obj is IController)
            {
                ((IController)obj).Init(server);
            }
            foreach (MethodInfo mi in controllerType.GetMethods(BindingFlags.Instance | BindingFlags.Public))
            {
                if (string.Compare("Equals", mi.Name, true) == 0 ||
                    string.Compare("GetHashCode", mi.Name, true) == 0 ||
                    string.Compare("GetType", mi.Name, true) == 0 ||
                    string.Compare("ToString", mi.Name, true) == 0 || mi.Name.IndexOf("set_") >= 0 ||
                    mi.Name.IndexOf("get_") >= 0)
                {
                    continue;
                }
                if (mi.GetCustomAttribute <NotActionAttribute>(false) != null)
                {
                    continue;
                }
                DataConvertAttribute actionConvert = mi.GetCustomAttribute <DataConvertAttribute>();
                if (mi.GetCustomAttribute <NoDataConvertAttribute>(false) != null)
                {
                    actionConvert = null;
                }
                else
                {
                    if (actionConvert == null)
                    {
                        actionConvert = controllerDataConvert;
                    }
                    if (actionConvert == null)
                    {
                        actionConvert = new JsonDataConvertAttribute();
                    }
                }

                string sourceUrl = rooturl + mi.Name;
                string url       = sourceUrl;
                if (server.ServerConfig.UrlIgnoreCase)
                {
                    url = sourceUrl.ToLower();
                }
                RouteTemplateAttribute ra = mi.GetCustomAttribute <RouteTemplateAttribute>(false);
                if (ra != null)
                {
                    string reurl = ra.Analysis(url);
                    if (reurl != null)
                    {
                        server.UrlRewrite.Add(reurl, url);
                    }
                }
                ActionHandler handler = GetAction(url);

                if (handler != null)
                {
                    server.Log(EventArgs.LogType.Error, "{0} already exists!duplicate definition {1}.{2}!", url, controllerType.Name,
                               mi.Name);
                    continue;
                }
                handler             = new ActionHandler(obj, mi);
                handler.DataConvert = actionConvert;
                handler.Route       = ra;
                if (mi.GetCustomAttribute <PostAttribute>(false) != null)
                {
                    handler.Method = "POST";
                }
                handler.SourceUrl = sourceUrl;
                handler.Filters.AddRange(filters);
                fas = mi.GetCustomAttributes <FilterAttribute>(false);
                handler.Filters.AddRange(fas);
                skipfilters = mi.GetCustomAttributes <SkipFilterAttribute>(false);
                foreach (SkipFilterAttribute item in skipfilters)
                {
                    RemoveFilter(handler.Filters, item.Types);
                }
                mMethods[url] = handler;
                server.Log(EventArgs.LogType.Info, "register {0}.{1} to {2}", controllerType.Name, mi.Name, url);
            }
        }
示例#21
0
 internal ActionContext(ActionHandler handler, IDataContext context)
 {
     mHandler    = handler;
     mFilters    = handler.Filters;
     DataContext = context;
 }
        private void Register(HttpOptions config, Type controllerType, object controller, string rooturl, HttpApiServer server, ControllerAttribute ca,
                              Action <EventActionRegistingArgs> callback)
        {
            DataConvertAttribute controllerDataConvert      = controllerType.GetCustomAttribute <DataConvertAttribute>(false);
            OptionsAttribute     controllerOptionsAttribute = controllerType.GetCustomAttribute <OptionsAttribute>(false);

            if (string.IsNullOrEmpty(rooturl))
            {
                rooturl = "/";
            }
            else
            {
                if (rooturl[0] != '/')
                {
                    rooturl = "/" + rooturl;
                }
                if (rooturl[rooturl.Length - 1] != '/')
                {
                    rooturl += "/";
                }
            }
            RequestMaxRPS          control_maxRPS = controllerType.GetCustomAttribute <RequestMaxRPS>();
            List <FilterAttribute> filters        = new List <FilterAttribute>();

            if (!ca.SkipPublicFilter)
            {
                filters.AddRange(config.Filters);
            }
            IEnumerable <FilterAttribute> fas = controllerType.GetCustomAttributes <FilterAttribute>(false);

            filters.AddRange(fas);
            LoadBaseFilter(controllerType, filters);
            IEnumerable <SkipFilterAttribute> skipfilters = controllerType.GetCustomAttributes <SkipFilterAttribute>(false);

            foreach (SkipFilterAttribute item in skipfilters)
            {
                RemoveFilter(filters, item.Types);
            }
            object obj = controller;

            if (obj is IController)
            {
                string path = System.IO.Path.GetDirectoryName(controllerType.Assembly.Location) + System.IO.Path.DirectorySeparatorChar;
                ((IController)obj).Init(server, path);
                if (server.EnableLog(EventArgs.LogType.Info))
                {
                    server.Log(EventArgs.LogType.Info, $"init {controllerType} controller path {path}");
                }
            }
            foreach (MethodInfo mi in controllerType.GetMethods(BindingFlags.Instance | BindingFlags.Public))
            {
                if (string.Compare("Equals", mi.Name, true) == 0 ||
                    string.Compare("GetHashCode", mi.Name, true) == 0 ||
                    string.Compare("GetType", mi.Name, true) == 0 ||
                    string.Compare("ToString", mi.Name, true) == 0 || mi.Name.IndexOf("set_") >= 0 ||
                    mi.Name.IndexOf("get_") >= 0)
                {
                    continue;
                }
                if (mi.GetCustomAttribute <NotActionAttribute>(false) != null)
                {
                    continue;
                }
                bool          noconvert = false;
                RequestMaxRPS maxRPS    = mi.GetCustomAttribute <RequestMaxRPS>();
                if (maxRPS == null)
                {
                    maxRPS = control_maxRPS;
                }
                DataConvertAttribute actionConvert          = mi.GetCustomAttribute <DataConvertAttribute>();
                OptionsAttribute     methodOptionsAttribute = mi.GetCustomAttribute <OptionsAttribute>();
                if (mi.GetCustomAttribute <NoDataConvertAttribute>(false) != null)
                {
                    noconvert     = true;
                    actionConvert = null;
                }
                else
                {
                    if (actionConvert == null)
                    {
                        actionConvert = controllerDataConvert;
                    }
                }
                string       sourceUrl = rooturl + mi.Name;
                string       url       = sourceUrl;
                string       method    = HttpParse.GET_TAG + "/" + HttpParse.POST_TAG;
                string       route     = null;
                GetAttribute get       = mi.GetCustomAttribute <GetAttribute>(false);
                if (get != null)
                {
                    method = HttpParse.GET_TAG;
                    route  = get.Route;
                }
                PostAttribute post = mi.GetCustomAttribute <PostAttribute>(false);
                if (post != null)
                {
                    method = HttpParse.POST_TAG;
                    route  = post.Route;
                }
                DelAttribute del = mi.GetCustomAttribute <DelAttribute>(false);
                if (del != null)
                {
                    method = HttpParse.DELETE_TAG;
                    route  = del.Route;
                }
                PutAttribute put = mi.GetCustomAttribute <PutAttribute>(false);
                if (put != null)
                {
                    method = HttpParse.PUT_TAG;
                    route  = put.Route;
                }

                //if (server.Options.UrlIgnoreCase)
                //{
                //    url = sourceUrl.ToLower();
                //}
                RouteTemplateAttribute ra = null;
                if (!string.IsNullOrEmpty(route))
                {
                    ra = new RouteTemplateAttribute(route);
                    string reurl;
                    if (route[0] == '/')
                    {
                        reurl = ra.Analysis(null);
                    }
                    else if (route[0] == '{')
                    {
                        reurl = ra.Analysis(url + "/");
                    }
                    else
                    {
                        reurl = ra.Analysis(route.IndexOf('/', 0) > 0 ? rooturl : url + "/");
                    }
                    if (reurl == null)
                    {
                        if (route[0] == '/')
                        {
                            reurl = route;
                        }
                        else
                        {
                            reurl = rooturl + route;
                        }
                    }
                    server.UrlRewrite.Add(null, reurl, url);
                }
                ActionHandler handler = GetAction(url);
                if (handler != null)
                {
                    if (server.EnableLog(EventArgs.LogType.Error))
                    {
                        server.Log(EventArgs.LogType.Error, $"{url} already exists! replaced with {controllerType.Name}.{mi.Name}!");
                    }
                }
                handler          = new ActionHandler(obj, mi, this.Server);
                handler.AuthMark = controllerType.GetCustomAttribute <AuthMarkAttribute>(false);
                var authmark = mi.GetCustomAttribute <AuthMarkAttribute>(false);
                if (authmark != null)
                {
                    handler.AuthMark = authmark;
                }
                if (handler.AuthMark == null)
                {
                    handler.AuthMark = new AuthMarkAttribute(AuthMarkType.None);
                }
                if (mi.ReturnType == typeof(Task) || mi.ReturnType.BaseType == typeof(Task))
                {
                    handler.Async = true;
                    PropertyInfo pi = mi.ReturnType.GetProperty("Result", BindingFlags.Public | BindingFlags.Instance);
                    if (pi != null)
                    {
                        handler.PropertyHandler = new PropertyHandler(pi);
                    }
                }
                handler.Path = rooturl;
                if (methodOptionsAttribute == null)
                {
                    handler.OptionsAttribute = controllerOptionsAttribute;
                }
                else
                {
                    handler.OptionsAttribute = methodOptionsAttribute;
                }
                if (handler.OptionsAttribute == null && !ca.SkipPublicFilter)
                {
                    handler.OptionsAttribute = handler.HttpApiServer.Options.CrossDomain;
                }
                handler.ThreadQueue = controllerType.GetCustomAttribute <ThreadQueueAttribute>(false);
                var queue = mi.GetCustomAttribute <ThreadQueueAttribute>(false);
                if (queue != null)
                {
                    handler.ThreadQueue = queue;
                }
                handler.NoConvert     = noconvert;
                handler.InstanceType  = ca.InstanceType;
                handler.DataConverter = actionConvert;
                handler.Route         = ra;
                handler.Method        = method;
                handler.SourceUrl     = sourceUrl;
                handler.Filters.AddRange(filters);
                fas = mi.GetCustomAttributes <FilterAttribute>(false);
                handler.Filters.AddRange(fas);
                handler.Url = url;
                if (maxRPS != null)
                {
                    handler.MaxRPS = maxRPS.Value;
                }
                int rpsSetting = server.Options.GetActionMaxrps(handler.SourceUrl);
                if (rpsSetting > 0)
                {
                    handler.MaxRPS = rpsSetting;
                }
                skipfilters = mi.GetCustomAttributes <SkipFilterAttribute>(false);
                foreach (SkipFilterAttribute item in skipfilters)
                {
                    RemoveFilter(handler.Filters, item.Types);
                }
                EventActionRegistingArgs registing = new EventActionRegistingArgs();
                registing.Url     = url;
                registing.Handler = handler;
                registing.Cancel  = false;
                registing.Server  = this.Server;
                callback?.Invoke(registing);
                if (!registing.Cancel)
                {
                    Server.OnActionRegisting(registing);
                }

                if (!registing.Cancel)
                {
                    AddHandlers(url, handler);
                    server.ActionSettings(handler);
                    if (server.EnableLog(EventArgs.LogType.Info))
                    {
                        server.Log(EventArgs.LogType.Info, $"register { controllerType.Name}.{mi.Name} to [{handler.Method}:{url}]");
                    }
                }
                else
                {
                    if (server.EnableLog(EventArgs.LogType.Info))
                    {
                        server.Log(EventArgs.LogType.Info, $"register { controllerType.Name}.{mi.Name} cancel ");
                    }
                }
            }
        }
示例#23
0
 public void ActionSettings(ActionHandler handler)
 {
     mActionSettings.SetAction(handler);
 }
示例#24
0
        private void Register(HttpConfig config, Type controllerType, object controller, string rooturl, HttpApiServer server, ControllerAttribute ca)
        {
            DataConvertAttribute controllerDataConvert = controllerType.GetCustomAttribute <DataConvertAttribute>(false);

            if (string.IsNullOrEmpty(rooturl))
            {
                rooturl = "/";
            }
            else
            {
                if (rooturl[0] != '/')
                {
                    rooturl = "/" + rooturl;
                }
                if (rooturl[rooturl.Length - 1] != '/')
                {
                    rooturl += "/";
                }
            }
            List <FilterAttribute> filters = new List <FilterAttribute>();

            filters.AddRange(config.Filters);
            IEnumerable <FilterAttribute> fas = controllerType.GetCustomAttributes <FilterAttribute>(false);

            filters.AddRange(fas);
            IEnumerable <SkipFilterAttribute> skipfilters = controllerType.GetCustomAttributes <SkipFilterAttribute>(false);

            foreach (SkipFilterAttribute item in skipfilters)
            {
                RemoveFilter(filters, item.Types);
            }
            object obj = controller;

            if (obj is IController)
            {
                ((IController)obj).Init(server);
            }
            foreach (MethodInfo mi in controllerType.GetMethods(BindingFlags.Instance | BindingFlags.Public))
            {
                if (string.Compare("Equals", mi.Name, true) == 0 ||
                    string.Compare("GetHashCode", mi.Name, true) == 0 ||
                    string.Compare("GetType", mi.Name, true) == 0 ||
                    string.Compare("ToString", mi.Name, true) == 0 || mi.Name.IndexOf("set_") >= 0 ||
                    mi.Name.IndexOf("get_") >= 0)
                {
                    continue;
                }
                if (mi.GetCustomAttribute <NotActionAttribute>(false) != null)
                {
                    continue;
                }
                bool noconvert = false;
                DataConvertAttribute actionConvert = mi.GetCustomAttribute <DataConvertAttribute>();
                if (mi.GetCustomAttribute <NoDataConvertAttribute>(false) != null)
                {
                    noconvert     = true;
                    actionConvert = null;
                }
                else
                {
                    if (actionConvert == null)
                    {
                        actionConvert = controllerDataConvert;
                    }
                }
                string       sourceUrl = rooturl + mi.Name;
                string       url       = sourceUrl;
                string       method    = HttpParse.GET_TAG;
                string       route     = null;
                GetAttribute get       = mi.GetCustomAttribute <GetAttribute>(false);
                if (get != null)
                {
                    method = HttpParse.GET_TAG;
                    route  = get.Route;
                }
                PostAttribute post = mi.GetCustomAttribute <PostAttribute>(false);
                if (post != null)
                {
                    method = HttpParse.POST_TAG;
                    route  = post.Route;
                }
                DelAttribute del = mi.GetCustomAttribute <DelAttribute>(false);
                if (del != null)
                {
                    method = HttpParse.DELETE_TAG;
                    route  = del.Route;
                }
                PutAttribute put = mi.GetCustomAttribute <PutAttribute>(false);
                if (put != null)
                {
                    method = HttpParse.PUT_TAG;
                    route  = put.Route;
                }

                if (server.ServerConfig.UrlIgnoreCase)
                {
                    url = sourceUrl.ToLower();
                }
                RouteTemplateAttribute ra = null;
                if (!string.IsNullOrEmpty(route))
                {
                    ra = new RouteTemplateAttribute(route);
                    string reurl = ra.Analysis(url);
                    if (reurl != null)
                    {
                        server.UrlRewrite.Add(reurl, url);
                    }
                }
                ActionHandler handler = GetAction(url);
                if (handler != null)
                {
                    server.Log(EventArgs.LogType.Warring, "{0} already exists!replaced with {1}.{2}!", url, controllerType.Name,
                               mi.Name);
                }
                handler                = new ActionHandler(obj, mi);
                handler.Path           = rooturl;
                handler.NoConvert      = noconvert;
                handler.SingleInstance = ca.SingleInstance;
                handler.DataConvert    = actionConvert;
                handler.Route          = ra;
                handler.Method         = method;
                handler.SourceUrl      = sourceUrl;
                handler.Filters.AddRange(filters);
                fas = mi.GetCustomAttributes <FilterAttribute>(false);
                handler.Filters.AddRange(fas);
                handler.Url = url;
                skipfilters = mi.GetCustomAttributes <SkipFilterAttribute>(false);
                foreach (SkipFilterAttribute item in skipfilters)
                {
                    RemoveFilter(handler.Filters, item.Types);
                }
                AddHandlers(url, handler);
                server.Log(EventArgs.LogType.Info, "register {0}.{1} to {2}", controllerType.Name, mi.Name, url);
            }
        }