Example #1
0
        public void Error(Exception e_, EventArgs.LogType logType = EventArgs.LogType.Error)
        {
            if (Server.EnableLog(logType))
            {
                Server.Log(logType,
                           $"{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);
        }
Example #2
0
 public void Error(Exception e_, EventArgs.LogType logType = EventArgs.LogType.Error)
 {
     if (Server.EnableLog(logType))
     {
         Server.Log(logType, "{0} ws execute {1} inner error {2}@{3}", Request.RemoteIPAddress, Request.Url, e_.Message, e_.StackTrace);
     }
     Result.Code  = 500;
     Result.Error = e_.Message;
     if (Server.Options.OutputStackTrace)
     {
         Result.StackTrace = e_.StackTrace;
     }
     DataFrame.Send(Request.Session);
 }
 public void Error(Exception e_, EventArgs.LogType logType = EventArgs.LogType.Error, int code = 500)
 {
     if (Server.EnableLog(logType))
     {
         Server.Log(logType, $"Websocket {Request.ID} {Request.RemoteIPAddress} execute {DataContext.ActionUrl} inner error {e_.Message}@{e_.StackTrace}");
     }
     Result.Code  = code;
     Result.Error = e_.Message;
     if (Server.Options.OutputStackTrace)
     {
         Result.StackTrace = e_.StackTrace;
     }
     DataFrame.Send(Request.Session, true);
 }
        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);
                    }
                }
            }
        }
Example #5
0
        public virtual void SetResponse(HttpRequest request, HttpResponse response)
        {
            HttpApiServer server = request.Server;

            if (server.EnableLog(EventArgs.LogType.Debug))
            {
                server.Log(EventArgs.LogType.Debug, $"{request.RemoteIPAddress} {request.Method} {request.Url} set options");
            }
            response.Header["Access-Control-Allow-Origin"] = AllowOrigin;
        }
Example #6
0
 public void Register(params Assembly[] assemblies)
 {
     foreach (Assembly item in assemblies)
     {
         Type[] types = item.GetTypes();
         foreach (Type type in types)
         {
             ControllerAttribute ca = type.GetCustomAttribute <ControllerAttribute>(false);
             if (ca != null)
             {
                 try
                 {
                     EventControllerInstanceArgs e = new EventControllerInstanceArgs();
                     e.Type = type;
                     OnControllerInstance(e);
                     if (e.Controller == null)
                     {
                         Register(Server.Options, type, Activator.CreateInstance(type), ca.BaseUrl, Server, ca);
                     }
                     else
                     {
                         Register(Server.Options, type, e.Controller, ca.BaseUrl, Server, ca);
                     }
                 }
                 catch (Exception e_)
                 {
                     if (Server.EnableLog(EventArgs.LogType.Error))
                     {
                         string msg = $"{type} controller register error {e_.Message} {e_.StackTrace}";
                         Server.Log(EventArgs.LogType.Error, msg);
                     }
                 }
             }
             ParameterBinderMapper mapper = type.GetCustomAttribute <ParameterBinderMapper>(false);
             if (mapper != null)
             {
                 RegisterParameterBinder(mapper.ParameterType, type);
             }
         }
     }
 }
Example #7
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);
                    }
                }
            }
        }
Example #8
0
 void IDataResponse.Write(PipeStream stream)
 {
     try
     {
         OnWrite(stream);
     }
     catch (Exception e_)
     {
         HttpApiServer server = Request.Server;
         if (server.EnableLog(EventArgs.LogType.Error))
         {
             server.Log(EventArgs.LogType.Error, $"{Request.RemoteIPAddress} {Request.Method} {Request.Url} response write data error {e_.Message}@{e_.StackTrace}");
             Request.Session.Dispose();
         }
     }
     finally
     {
         Request.Recovery();
     }
 }
Example #9
0
        private void Add(UrlRoute item)
        {
            if (mServer.EnableLog(EventArgs.LogType.Info))
            {
                mServer.Log(EventArgs.LogType.Info, "rewrite setting {0} to {1}", item.Url, item.Rewrite);
            }
            item.UrlIgnoreCase = this.UrlIgnoreCase;
            item.Init();

            RouteGroup rg = null;

            mRoutes.TryGetValue(item.ID, out rg);
            if (rg == null)
            {
                rg               = new RouteGroup();
                rg.Ext           = item.Ext;
                mRoutes[item.ID] = rg;
            }
            rg.Routes.Add(item);
        }
Example #10
0
 void IDataResponse.Write(PipeStream stream)
 {
     try
     {
         OnWrite(stream);
     }
     catch (Exception e_)
     {
         HttpApiServer server = Request.Server;
         if (server.EnableLog(EventArgs.LogType.Error))
         {
             server.Log(EventArgs.LogType.Error, $"{Request.RemoteIPAddress} {Request.Method} {Request.Url} response write data error {e_.Message}@{e_.StackTrace}");
             Request.Session.Dispose();
         }
     }
     finally
     {
         Request.Server.IncrementResponsed(Request, this, TimeWatch.GetTotalMilliseconds() - Request.RequestTime, int.Parse(this.Code), CodeMsg);
         Request.Recovery();
     }
 }
        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);
                }
            }
        }
        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);
        }
        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);
                    }
                }
Example #14
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);
        }
        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 ");
                    }
                }
            }
        }
Example #16
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);
                    }
                }
            }
        }