Esempio n. 1
0
 void context_PostMapRequestHandler(object sender, EventArgs e)
 {
     if (QueryTool.IsTaurusSuffix())
     {
         context.Handler = SessionHandler.Instance;//注册Session
     }
 }
Esempio n. 2
0
 void context_Error(object sender, EventArgs e)
 {
     if (QueryTool.IsTaurusSuffix())
     {
         Log.WriteLogToTxt(HttpContext.Current.Error);
     }
 }
Esempio n. 3
0
        private void InvokeClass()
        {
            Type t = null;

            //ViewController是由页面的前两个路径决定了。
            string[] items     = QueryTool.GetLocalPath().Trim('/').Split('/');
            string   className = InvokeLogic.Default;

            if (RouteConfig.RouteMode == 1)
            {
                className = items[0];
            }
            else if (RouteConfig.RouteMode == 2)
            {
                className = items.Length > 1 ? items[1] : "";
            }
            t = InvokeLogic.GetType(className);
            if (t == null)
            {
                WriteError("You need a controller for coding!");
            }
            try
            {
                object o = Activator.CreateInstance(t);//实例化
                t.GetMethod("ProcessRequest").Invoke(o, new object[] { context });
            }
            catch (ThreadAbortException e)
            {
                //ASP.NET 的机制就是通过异常退出线程(不要觉的奇怪)
            }
            catch (Exception err)
            {
                WriteError(err.Message);
            }
        }
Esempio n. 4
0
 private void CheckCORS(HttpContext context)
 {
     if (QueryTool.IsAllowCORS())
     {
         if (context.Request.HttpMethod == "OPTIONS")
         {
             context.Response.StatusCode = 204;
             context.Response.AppendHeader("Access-Control-Allow-Method", "GET,POST,PUT,DELETE");
             context.Response.AppendHeader("Access-Control-Allow-Origin", "*");
             if (context.Request.Headers["Access-Control-Allow-Headers"] != null)
             {
                 context.Response.AppendHeader("Access-Control-Allow-Headers", context.Request.Headers["Access-Control-Allow-Headers"]);
             }
             else if (context.Request.Headers["Access-Control-Request-Headers"] != null)
             {
                 context.Response.AppendHeader("Access-Control-Allow-Headers", context.Request.Headers["Access-Control-Request-Headers"]);
             }
             context.Response.End();
         }
         else if (context.Request.UrlReferrer == null || context.Request.Url.Authority != context.Request.UrlReferrer.Authority)
         {
             //跨域访问
             context.Response.AppendHeader("Access-Control-Allow-Origin", "*");
             context.Response.AppendHeader("Access-Control-Allow-Credentials", "true");
         }
     }
 }
Esempio n. 5
0
 void ReplaceOutput(HttpContext context)
 {
     if (QueryTool.IsSubAppSite(context.Request.Url))
     {
         //如果项目需要部署成子应用程序,则开启,否则不需要开启(可注释掉下面一行代码)
         context.Response.Filter = new HttpResponseFilter(context.Response.Filter);
     }
 }
Esempio n. 6
0
        void context_Error(object sender, EventArgs e)
        {
            HttpContext cont = ((HttpApplication)sender).Context;

            if (cont != null && QueryTool.IsCallMvc(cont.Request.Url) && QueryTool.IsTaurusSuffix(cont.Request.Url))
            {
                Log.WriteLogToTxt(cont.Error);
            }
        }
Esempio n. 7
0
        void context_PostMapRequestHandler(object sender, EventArgs e)
        {
            HttpContext cont = ((HttpApplication)sender).Context;

            if (cont != null && QueryTool.IsCallMvc(cont.Request.Url) && !QueryTool.IsProxyCall(cont) && QueryTool.IsTaurusSuffix(cont.Request.Url))
            {
                cont.Handler = SessionHandler.Instance;//注册Session
            }
        }
Esempio n. 8
0
 void context_AcquireRequestState(object sender, EventArgs e)
 {
     if (QueryTool.IsTaurusSuffix())
     {
         CheckCORS();
         ReplaceOutput();
         InvokeClass();
     }
 }
Esempio n. 9
0
        private void Init(Type t)
        {
            _ControllerName = t.Name.Replace(Const.Controller, "").ToLower();
            string[] items = QueryTool.GetLocalPath(Request.Url).Trim('/').Split('/');
            firstPara = items[0];
            int    paraStartIndex = RouteConfig.RouteMode + 1;
            string methodName     = string.Empty;

            switch (RouteConfig.RouteMode)
            {
            case 0:
                methodName = items[0];
                break;

            case 1:
                if (items.Length > 1)
                {
                    if (items.Length > 2 && items[0].ToLower() != _ControllerName && items[1].ToLower() == _ControllerName && items[0] == MicroService.Config.ClientName.ToLower())
                    {
                        paraStartIndex++;
                        methodName = items[2];    //往后兼容一格。
                    }
                    else
                    {
                        methodName = items[1];
                    }
                }
                break;

            case 2:
                _Module = items[0];
                if (items.Length > 2)
                {
                    methodName = items[2];
                }
                else if (items.Length > 1)
                {
                    //兼容【路由1=》(变更为)2】
                    methodName = items[1];
                }
                break;
            }
            _Action = methodName;


            if (items.Length > paraStartIndex)
            {
                _ParaItems = new string[items.Length - paraStartIndex];
                Array.Copy(items, paraStartIndex, _ParaItems, 0, _ParaItems.Length);
            }
            else
            {
                _ParaItems    = new string[1];
                _ParaItems[0] = "";
            }
        }
Esempio n. 10
0
        void context_PostMapRequestHandler(object sender, EventArgs e)
        {
            HttpApplication app = (HttpApplication)sender;

            context = app.Context;
            if (QueryTool.IsTaurusSuffix())
            {
                context.Handler = SessionHandler.Instance;//注册Session
            }
        }
Esempio n. 11
0
 void context_BeginRequest(object sender, EventArgs e)
 {
     if (QueryTool.IsTaurusSuffix())
     {
         HttpApplication app = (HttpApplication)sender;
         context = app.Context;
         ReplaceOutput();
         InvokeClass();
     }
 }
Esempio n. 12
0
        void context_AcquireRequestState(object sender, EventArgs e)
        {
            HttpContext cont = ((HttpApplication)sender).Context;

            if (cont != null && QueryTool.IsCallMvc(cont.Request.Url) && !QueryTool.IsProxyCall(cont) && QueryTool.IsTaurusSuffix(cont.Request.Url))
            {
                CheckCORS(cont);
                ReplaceOutput(cont);
                InvokeClass(cont);
            }
        }
Esempio n. 13
0
        void context_BeginRequest(object sender, EventArgs e)
        {
            HttpApplication app     = (HttpApplication)sender;
            HttpContext     context = app.Context;
            Uri             uri     = context.Request.Url;

            #region 微服务检测与启动
            string urlAbs  = uri.AbsoluteUri;
            string urlPath = uri.PathAndQuery;
            string host    = urlAbs.Substring(0, urlAbs.Length - urlPath.Length);
            MicroService.Run.Start(host);//微服务检测、启动。
            if (!QueryTool.IsCallMicroServiceReg(uri) && MicroService.Run.Proxy(context, true))
            {
                QueryTool.SetRunProxySuccess(context);
                try
                {
                    context.Response.End();
                }
                catch (ThreadAbortException)
                {
                }

                return;
            }
            #endregion

            if (QueryTool.IsCallMvc(uri))
            {
                if (context.Request.Url.LocalPath == "/")//设置默认首页
                {
                    string defaultUrl = QueryTool.GetDefaultUrl();
                    if (!string.IsNullOrEmpty(defaultUrl))
                    {
                        context.RewritePath(defaultUrl);
                        return;
                    }
                }
                if (QueryTool.IsTaurusSuffix(uri))
                {
                    MethodInfo routeMapInvoke = MethodCollector.RouteMapInvokeMethod;
                    if (routeMapInvoke != null)
                    {
                        string url = Convert.ToString(routeMapInvoke.Invoke(null, new object[] { context.Request }));
                        if (!string.IsNullOrEmpty(url))
                        {
                            context.RewritePath(url);
                        }
                    }
                }
            }
        }
Esempio n. 14
0
 private bool GetInvokeParas(MethodInfo method, out object[] paras)
 {
     paras = null;
     #region 增加处理参数支持
     ParameterInfo[] piList       = method.GetParameters();
     object[]        validateList = method.GetCustomAttributes(typeof(ValidateAttribute), true);
     if (piList != null && piList.Length > 0)
     {
         paras = new object[piList.Length];
         for (int i = 0; i < piList.Length; i++)
         {
             ParameterInfo pi    = piList[i];
             Type          t     = pi.ParameterType;
             string        value = Query <string>(pi.Name, null);
             if (value == null)
             {
                 if (t.IsValueType && t.IsGenericType && t.FullName.StartsWith("System.Nullable"))
                 {
                     continue;
                 }
                 if (ReflectTool.GetSystemType(ref t) != SysType.Base)//基础值类型
                 {
                     value = GetJson();
                 }
             }
             //检测是否允许为空,是否满足正则格式。
             if (!ValidateParas(validateList, pi.Name, value))
             {
                 return(false);
             }
             try
             {
                 paras[i] = QueryTool.ChangeType(value, t);//类型转换(基础或实体)
             }
             catch (Exception err)
             {
                 string typeName = t.Name;
                 if (typeName.StartsWith("Nullable"))
                 {
                     typeName = Nullable.GetUnderlyingType(t).Name;
                 }
                 string outMsg = string.Format("[{0} {1} = {2}]  [Error : {3}]", typeName, pi.Name, value, err.Message);
                 Write(outMsg, false);
                 return(false);
             }
         }
     }
     #endregion
     return(true);
 }
Esempio n. 15
0
        void context_BeginRequest(object sender, EventArgs e)
        {
            HttpApplication app = (HttpApplication)sender;

            context = app.Context;
            if (context.Request.Url.LocalPath == "/")//设置默认首页
            {
                string defaultUrl = QueryTool.GetDefaultUrl();
                if (!string.IsNullOrEmpty(defaultUrl))
                {
                    context.RewritePath(defaultUrl, false);
                }
            }
        }
Esempio n. 16
0
        private void InvokeClass(HttpContext context)
        {
            Type t = null;

            //ViewController是由页面的前两个路径决定了。
            string[] items     = QueryTool.GetLocalPath(context.Request.Url).Trim('/').Split('/');
            string   className = Const.Default;

            if (RouteConfig.RouteMode == 1)
            {
                className = items.Length > 2 ? items[0] + "." + items[1] : items[0];
            }
            else if (RouteConfig.RouteMode == 2)
            {
                className = items.Length > 1 ? items[0] + "." + items[1] : items[0];
            }
            t = ControllerCollector.GetController(className);
            if (t == null || t.Name == Const.DefaultController)
            {
                if (MicroService.Run.Proxy(context, false))//客户端做为网关。
                {
                    return;
                }
            }
            if (t == null)
            {
                WriteError("You need a " + className + " controller for coding!", context);
            }
            else
            {
                try
                {
                    object o = Activator.CreateInstance(t);//实例化
                    t.GetMethod("ProcessRequest").Invoke(o, new object[] { context });
                }

                catch (ThreadAbortException e)
                {
                    //内部提前Response.End()时引发的异常
                    //ASP.NET 的机制就是通过异常退出线程(不要觉的奇怪)
                }
                catch (Exception err)
                {
                    WriteError(err.Message, context);
                }
            }
            //context.Response.End();
        }
 private object[] GetInvokeParas(MethodInfo method)
 {
     object[] paras = null;
     #region 增加处理参数支持
     ParameterInfo[] piList = method.GetParameters();
     if (piList != null && piList.Length > 0)
     {
         paras = new object[piList.Length];
         for (int i = 0; i < piList.Length; i++)
         {
             ParameterInfo pi    = piList[i];
             Type          t     = pi.ParameterType;
             string        value = Query <string>(pi.Name, null);
             if (value == null)
             {
                 if (t.IsValueType && t.IsGenericType && t.FullName.StartsWith("System.Nullable"))
                 {
                     continue;
                 }
                 if (ReflectTool.GetSystemType(ref t) != SysType.Base)//基础值类型
                 {
                     value = GetJson();
                 }
             }
             try
             {
                 paras[i] = QueryTool.ChangeType(value, t);//类型转换(基础或实体)
             }
             catch (Exception err)
             {
                 string typeName = t.Name;
                 if (typeName.StartsWith("Nullable"))
                 {
                     typeName = Nullable.GetUnderlyingType(t).Name;
                 }
                 string outMsg = string.Format("[{0} {1} = {2}]  [Error : {3}]", typeName, pi.Name, value, err.Message);
                 Write(outMsg, false);
                 // context.Response.Write(outMsg);
                 context.Response.End();
                 break;
             }
         }
     }
     #endregion
     return(paras);
 }
Esempio n. 18
0
        public void ProcessRequest(HttpContext context)
        {
            this.context = context;
            try
            {
                Type     t          = _ControllerType = this.GetType();
                string[] items      = QueryTool.GetLocalPath().Trim('/').Split('/');
                string   methodName = string.Empty;
                switch (RouteConfig.RouteMode)
                {
                case 0:
                    methodName = items[0];
                    break;

                case 1:
                    if (items.Length > 1)
                    {
                        methodName = items[1];
                    }
                    break;

                case 2:
                    if (items.Length > 2)
                    {
                        methodName = items[2];
                    }
                    break;
                }
                bool       hasTokenAttr = false;
                MethodInfo method       = InvokeLogic.GetMethod(t, methodName, out hasTokenAttr);
                if (method != null)
                {
                    bool isGoOn = true;
                    if (hasTokenAttr && InvokeLogic.CheckTokenMethod != null)
                    { //CheckToken
                        isGoOn = Convert.ToBoolean(InvokeLogic.CheckTokenMethod.Invoke(null, new object[] { this, methodName }));
                    }
                    if (isGoOn)
                    {
                        _Action = method.Name;
                        BeforeInvoke(method.Name);
                        if (!CancelLoadHtml)
                        {
                            _View = ViewEngine.Create(t.Name, method.Name);
                        }
                        if (!CancelInvoke)
                        {
                            method.Invoke(this, null);
                            if (IsHttpPost)
                            {
                                string name = GetBtnName();
                                if (!string.IsNullOrEmpty(name))
                                {
                                    MethodInfo postBtnMethod = InvokeLogic.GetMethod(t, name);
                                    if (postBtnMethod != null && postBtnMethod.Name != InvokeLogic.Default)
                                    {
                                        postBtnMethod.Invoke(this, null);
                                    }
                                }
                            }
                            if (!CancelInvoke)
                            {
                                EndInvoke(method.Name);
                            }
                        }
                    }
                    if (View != null)
                    {
                        context.Response.Write(View.OutXml);
                    }
                    else if (apiResult.Length > 0)
                    {
                        context.Response.Write(apiResult.ToString());
                    }
                }
            }
            catch (System.Threading.ThreadAbortException)
            {
                return;
            }
            catch (Exception err)
            {
                WriteError(err.Message);
                context.Response.Write(err.Message);
            }

            context.Response.End();
        }
Esempio n. 19
0
        public void ProcessRequest(HttpContext context)
        {
            this.context = context;
            try
            {
                Type t = _ControllerType = this.GetType();
                #region GetMethodName
                string[] items      = QueryTool.GetLocalPath().Trim('/').Split('/');
                string   methodName = string.Empty;
                switch (RouteConfig.RouteMode)
                {
                case 0:
                    methodName = items[0];
                    break;

                case 1:
                    if (items.Length > 1)
                    {
                        methodName = items[1];
                    }
                    break;

                case 2:
                    _Module = items[0];
                    if (items.Length > 2)
                    {
                        methodName = items[2];
                    }
                    break;
                }
                _Action = methodName;
                #endregion
                bool isGoOn = true;

                char[]     attrFlags;
                MethodInfo method = InvokeLogic.GetMethod(t, methodName, out attrFlags);
                if (method != null)
                {
                    if (attrFlags[0] == '1')
                    {
                        #region Validate CheckToken
                        MethodInfo checkToken = InvokeLogic.GetMethod(t, InvokeLogic.Const.CheckToken);
                        if (checkToken != null && checkToken.Name == InvokeLogic.Const.CheckToken)
                        {
                            isGoOn = Convert.ToBoolean(checkToken.Invoke(this, null));
                        }
                        else if (InvokeLogic.DefaultCheckToken != null)
                        {
                            isGoOn = Convert.ToBoolean(InvokeLogic.DefaultCheckToken.Invoke(null, new object[] { this, methodName }));
                        }
                        else if (InvokeLogic.AuthCheckToken != null)
                        {
                            isGoOn = Convert.ToBoolean(InvokeLogic.AuthCheckToken.Invoke(null, new object[] { this }));
                        }
                        #endregion
                    }
                    if (isGoOn)//配置了HttpGet或HttpPost
                    {
                        #region Validate Http methods
                        string[] httpMethods = InvokeLogic.HttpMethods;
                        for (int i = 0; i < httpMethods.Length; i++)
                        {
                            if (attrFlags[i + 1] == '1')
                            {
                                isGoOn = false;
                                if (httpMethods[i] == Request.HttpMethod)
                                {
                                    isGoOn = true;
                                    break;
                                }
                            }
                        }
                        if (!isGoOn)
                        {
                            Write("Http method not support " + Request.HttpMethod, false);
                        }
                        #endregion
                    }
                    if (isGoOn)
                    {
                        #region Method Invoke


                        #region BeforeInvoke
                        MethodInfo beforeInvoke = InvokeLogic.GetMethod(t, InvokeLogic.Const.BeforeInvoke);
                        if (beforeInvoke != null && beforeInvoke.Name == InvokeLogic.Const.BeforeInvoke)
                        {
                            isGoOn = Convert.ToBoolean(beforeInvoke.Invoke(this, new object[] { method.Name }));
                        }
                        else if (InvokeLogic.BeforeInvokeMethod != null)
                        {
                            isGoOn = Convert.ToBoolean(InvokeLogic.BeforeInvokeMethod.Invoke(null, new object[] { this, methodName }));
                        }
                        #endregion

                        //BeforeInvoke(method.Name);

                        if (!CancelLoadHtml)
                        {
                            _View = ViewEngine.Create(t.Name, method.Name);
                        }

                        if (isGoOn)
                        {
                            object[] paras;
                            if (GetInvokeParas(method, out paras))
                            {
                                method.Invoke(this, paras);
                                if (IsHttpPost)
                                {
                                    #region Button Invoke
                                    string name = GetBtnName();
                                    if (!string.IsNullOrEmpty(name))
                                    {
                                        MethodInfo postBtnMethod = InvokeLogic.GetMethod(t, name);
                                        if (postBtnMethod != null && postBtnMethod.Name != InvokeLogic.Const.Default)
                                        {
                                            GetInvokeParas(postBtnMethod, out paras);
                                            postBtnMethod.Invoke(this, paras);
                                        }
                                    }
                                    #endregion
                                }
                                if (isGoOn)
                                {
                                    #region EndInvoke
                                    MethodInfo endInvoke = InvokeLogic.GetMethod(t, InvokeLogic.Const.EndInvoke);
                                    if (endInvoke != null && endInvoke.Name == InvokeLogic.Const.EndInvoke)
                                    {
                                        isGoOn = Convert.ToBoolean(endInvoke.Invoke(this, new object[] { method.Name }));
                                    }
                                    else if (InvokeLogic.EndInvokeMethod != null)
                                    {
                                        InvokeLogic.EndInvokeMethod.Invoke(null, new object[] { this, methodName });
                                    }
                                    #endregion
                                    if (InvokeLogic.DocRecord != null)
                                    {
                                        InvokeLogic.DocRecord.Invoke(null, new object[] { this, methodName });
                                    }
                                }
                            }
                        }
                        #endregion
                    }
                }
                if (string.IsNullOrEmpty(context.Response.Charset))
                {
                    context.Response.Charset = "utf-8";
                }
                if (View != null)
                {
                    context.Response.Write(View.OutXml);
                }
                else if (apiResult.Length > 0)
                {
                    if (apiResult[0] == '{' && apiResult[apiResult.Length - 1] == '}')
                    {
                        context.Response.ContentType = "application/json";
                    }
                    context.Response.Write(apiResult.ToString());
                }
            }
            catch (System.Threading.ThreadAbortException)
            {
                return;
            }
            catch (Exception err)
            {
                string errMssg = err.InnerException != null ? err.InnerException.Message : err.Message;
                WriteLog(errMssg);
                if (View == null)
                {
                    errMssg = JsonHelper.OutResult(false, errMssg);
                }
                context.Response.Write(errMssg);
            }
        }
Esempio n. 20
0
        public void ProcessRequest(HttpContext context)
        {
            this.context = context;
            try
            {
                Type     t          = _ControllerType = this.GetType();
                string[] items      = QueryTool.GetLocalPath().Trim('/').Split('/');
                string   methodName = string.Empty;
                switch (RouteConfig.RouteMode)
                {
                case 0:
                    methodName = items[0];
                    break;

                case 1:
                    if (items.Length > 1)
                    {
                        methodName = items[1];
                    }
                    break;

                case 2:
                    if (items.Length > 2)
                    {
                        methodName = items[2];
                    }
                    break;
                }
                bool isGoOn = true;
                //if (InvokeLogic.BeforeInvokeMethod != null)
                //{
                //    isGoOn = Convert.ToBoolean(InvokeLogic.BeforeInvokeMethod.Invoke(null, new object[] { this, methodName }));
                //}
                //if (isGoOn)
                //{
                char[]     attrFlags;
                MethodInfo method = InvokeLogic.GetMethod(t, methodName, out attrFlags);
                if (method != null)
                {
                    if (attrFlags[0] == '1')
                    {
                        #region Invoke CheckToken
                        MethodInfo checkToken = InvokeLogic.GetMethod(t, InvokeLogic.CheckToken);
                        if (checkToken != null && checkToken.Name == InvokeLogic.CheckToken)
                        {
                            isGoOn = Convert.ToBoolean(checkToken.Invoke(this, null));
                        }
                        else if (InvokeLogic.CheckTokenMethod != null)
                        {
                            isGoOn = Convert.ToBoolean(InvokeLogic.CheckTokenMethod.Invoke(null, new object[] { this, methodName }));
                        }
                        #endregion
                    }
                    if (isGoOn && attrFlags[1] != attrFlags[2])//配置了HttpGet或HttpPost
                    {
                        if (attrFlags[1] == '1' && !IsHttpGet)
                        {
                            isGoOn = false;
                            Write("Only support HttpGet!", false);
                        }
                        else if (attrFlags[2] == '1' && !IsHttpPost)
                        {
                            isGoOn = false;
                            Write("Only support HttpPost!", false);
                        }
                    }
                    if (isGoOn)
                    {
                        #region Method Invoke
                        _Action = method.Name;

                        MethodInfo beforeInvoke = InvokeLogic.GetMethod(t, InvokeLogic.BeforeInvoke);
                        if (beforeInvoke != null && beforeInvoke.Name == InvokeLogic.BeforeInvoke)
                        {
                            isGoOn = Convert.ToBoolean(beforeInvoke.Invoke(this, new object[] { method.Name }));
                        }
                        else if (InvokeLogic.BeforeInvokeMethod != null)
                        {
                            isGoOn = Convert.ToBoolean(InvokeLogic.BeforeInvokeMethod.Invoke(null, new object[] { this, methodName }));
                        }

                        //BeforeInvoke(method.Name);

                        if (!CancelLoadHtml)
                        {
                            _View = ViewEngine.Create(t.Name, method.Name);
                        }
                        if (isGoOn)
                        {
                            method.Invoke(this, GetInvokeParas(method));
                            if (IsHttpPost)
                            {
                                string name = GetBtnName();
                                if (!string.IsNullOrEmpty(name))
                                {
                                    MethodInfo postBtnMethod = InvokeLogic.GetMethod(t, name);
                                    if (postBtnMethod != null && postBtnMethod.Name != InvokeLogic.Default)
                                    {
                                        postBtnMethod.Invoke(this, GetInvokeParas(postBtnMethod));
                                    }
                                }
                            }
                            if (isGoOn)
                            {
                                MethodInfo endInvoke = InvokeLogic.GetMethod(t, InvokeLogic.EndInvoke);
                                if (endInvoke != null && endInvoke.Name == InvokeLogic.EndInvoke)
                                {
                                    isGoOn = Convert.ToBoolean(endInvoke.Invoke(this, new object[] { method.Name }));
                                }
                                else if (InvokeLogic.EndInvokeMethod != null)
                                {
                                    InvokeLogic.EndInvokeMethod.Invoke(null, new object[] { this, methodName });
                                }
                                // EndInvoke(method.Name);
                            }
                        }
                        #endregion
                    }
                }

                //}
                if (string.IsNullOrEmpty(context.Response.Charset))
                {
                    context.Response.Charset = "utf-8";
                }
                if (View != null)
                {
                    context.Response.Write(View.OutXml);
                }
                else if (apiResult.Length > 0)
                {
                    if (apiResult[0] == '{' && apiResult[apiResult.Length - 1] == '}')
                    {
                        context.Response.ContentType = "application/json";
                    }
                    context.Response.Write(apiResult.ToString());
                }
            }
            catch (System.Threading.ThreadAbortException)
            {
                return;
            }
            catch (Exception err)
            {
                string errMssg = err.InnerException != null ? err.InnerException.Message : err.Message;
                WriteLog(errMssg);
                context.Response.Write(errMssg);
            }
        }
Esempio n. 21
0
 private bool GetInvokeParas(MethodInfo method, out object[] paras)
 {
     paras = null;
     #region 增加处理参数支持
     ParameterInfo[] piList       = method.GetParameters();
     object[]        validateList = method.GetCustomAttributes(typeof(RequireAttribute), true);
     if (piList != null && piList.Length > 0)
     {
         paras = new object[piList.Length];
         for (int i = 0; i < piList.Length; i++)
         {
             ParameterInfo pi    = piList[i];
             Type          t     = pi.ParameterType;
             object        value = Query <object>(pi.Name, null);
             if (value == null)
             {
                 if (t.IsValueType && t.IsGenericType && t.FullName.StartsWith("System.Nullable"))
                 {
                     continue;
                 }
                 if (t.Name == "HttpPostedFile")
                 {
                     if (Request.Files != null && Request.Files.Count == 1)
                     {
                         value = Request.Files[0];
                     }
                 }
                 else if (piList.Length == 1 && ReflectTool.GetSystemType(ref t) != SysType.Base)//基础值类型
                 {
                     value = GetJson();
                 }
             }
             //检测是否允许为空,是否满足正则格式。
             if (!ValidateParas(validateList, pi.Name, Convert.ToString(value)))
             {
                 return(false);
             }
             try
             {
                 //特殊值处理
                 if (t.Name == "HttpPostedFile" && value is string && Convert.ToString(value) == DocSettings.DocDefaultImg.ToLower())
                 {
                     string path = DocSettings.DefaultImg;
                     if (!string.IsNullOrEmpty(path))
                     {
                         paras[i] = HttpPostedFileExtend.Create(path);
                     }
                 }
                 else
                 {
                     paras[i] = QueryTool.ChangeType(value, t);//类型转换(基础或实体)
                 }
             }
             catch (Exception err)
             {
                 string typeName = t.Name;
                 if (typeName.StartsWith("Nullable"))
                 {
                     typeName = Nullable.GetUnderlyingType(t).Name;
                 }
                 string outMsg = string.Format("[{0} {1} = {2}]  [Error : {3}]", typeName, pi.Name, value, err.Message);
                 Write(outMsg, false);
                 return(false);
             }
         }
     }
     //对未验证过的参数,再进行一次验证。
     foreach (object item in validateList)
     {
         RequireAttribute valid = item as RequireAttribute;
         if (!valid.isValidated)
         {
             if (valid.paraName.IndexOf(',') > -1)
             {
                 foreach (string name in valid.paraName.Split(','))
                 {
                     if (string.IsNullOrEmpty(Query <string>(name)))
                     {
                         Write(string.Format(valid.emptyTip, name), false);
                         return(false);
                     }
                 }
             }
             else if (!ValidateParas(validateList, valid.paraName, Query <string>(valid.paraName)))
             {
                 return(false);
             }
         }
     }
     validateList = null;
     #endregion
     return(true);
 }
Esempio n. 22
0
        public void ProcessRequest(HttpContext context)
        {
            this.context = context;
            try
            {
                Type t = _ControllerType = this.GetType();
                #region GetMethodName
                string[] items      = QueryTool.GetLocalPath().Trim('/').Split('/');
                string   methodName = string.Empty;
                switch (RouteConfig.RouteMode)
                {
                case 0:
                    methodName = items[0];
                    break;

                case 1:
                    if (items.Length > 1)
                    {
                        methodName = items[1];
                    }
                    break;

                case 2:
                    _Module = items[0];
                    if (items.Length > 2)
                    {
                        methodName = items[2];
                    }
                    break;
                }
                _Action = methodName;
                #endregion
                bool isGoOn = true;

                AttributeList attrFlags;
                MethodInfo    method = InvokeLogic.GetMethod(t, methodName, out attrFlags);
                if (method != null)
                {
                    if (isGoOn)//配置了HttpGet或HttpPost
                    {
                        isGoOn = attrFlags.HasKey(Request.HttpMethod);
                        if (!isGoOn)
                        {
                            Write("Http method not support " + Request.HttpMethod, false);
                        }
                    }
                    if (isGoOn && attrFlags.HasAck)//有[Ack]
                    {
                        #region Validate CheckAck
                        MethodInfo checkAck = InvokeLogic.GetMethod(t, InvokeLogic.Const.CheckAck);
                        if (checkAck != null && checkAck.Name == InvokeLogic.Const.CheckAck)
                        {
                            isGoOn = Convert.ToBoolean(checkAck.Invoke(this, null));
                        }
                        else if (InvokeLogic.DefaultCheckAck != null)
                        {
                            isGoOn = Convert.ToBoolean(InvokeLogic.DefaultCheckAck.Invoke(null, new object[] { this, methodName }));
                        }
                        #endregion
                    }
                    if (isGoOn && attrFlags.HasToken)//有[Token]
                    {
                        #region Validate CheckToken
                        MethodInfo checkToken = InvokeLogic.GetMethod(t, InvokeLogic.Const.CheckToken);
                        if (checkToken != null && checkToken.Name == InvokeLogic.Const.CheckToken)
                        {
                            isGoOn = Convert.ToBoolean(checkToken.Invoke(this, null));
                        }
                        else if (InvokeLogic.DefaultCheckToken != null)
                        {
                            isGoOn = Convert.ToBoolean(InvokeLogic.DefaultCheckToken.Invoke(null, new object[] { this, methodName }));
                        }
                        else if (InvokeLogic.AuthCheckToken != null)
                        {
                            isGoOn = Convert.ToBoolean(InvokeLogic.AuthCheckToken.Invoke(null, new object[] { this }));
                        }
                        #endregion
                    }
                    if (isGoOn)
                    {
                        #region Method Invoke


                        #region BeforeInvoke
                        if (InvokeLogic.BeforeInvokeMethod != null)//先调用全局
                        {
                            isGoOn = Convert.ToBoolean(InvokeLogic.BeforeInvokeMethod.Invoke(null, new object[] { this, methodName }));
                        }
                        if (isGoOn)
                        {
                            MethodInfo beforeInvoke = InvokeLogic.GetMethod(t, InvokeLogic.Const.BeforeInvoke);
                            if (beforeInvoke != null && beforeInvoke.Name == InvokeLogic.Const.BeforeInvoke)
                            {
                                isGoOn = Convert.ToBoolean(beforeInvoke.Invoke(this, new object[] { method.Name }));
                            }
                        }
                        #endregion

                        //BeforeInvoke(method.Name);

                        if (!CancelLoadHtml)
                        {
                            _View = ViewEngine.Create(t.Name, method.Name);
                            if (_View != null)
                            {
                                //追加几个全局标签变量
                                _View.KeyValue.Add("module", Module.ToLower());
                                _View.KeyValue.Add("controller", ControllerType.Name.ToLower());
                                _View.KeyValue.Add("action", Action.ToLower());
                                _View.KeyValue.Add("para", Para.ToLower());
                            }
                        }

                        if (isGoOn)
                        {
                            object[] paras;
                            if (GetInvokeParas(method, out paras))
                            {
                                method.Invoke(this, paras);
                                if (IsHttpPost)
                                {
                                    #region Button Invoke
                                    string name = GetBtnName();
                                    if (!string.IsNullOrEmpty(name))
                                    {
                                        MethodInfo postBtnMethod = InvokeLogic.GetMethod(t, name);
                                        if (postBtnMethod != null && postBtnMethod.Name != InvokeLogic.Const.Default)
                                        {
                                            GetInvokeParas(postBtnMethod, out paras);
                                            postBtnMethod.Invoke(this, paras);
                                        }
                                    }
                                    #endregion
                                }
                                if (isGoOn)
                                {
                                    #region EndInvoke
                                    MethodInfo endInvoke = InvokeLogic.GetMethod(t, InvokeLogic.Const.EndInvoke);
                                    if (endInvoke != null && endInvoke.Name == InvokeLogic.Const.EndInvoke)
                                    {
                                        endInvoke.Invoke(this, new object[] { method.Name });
                                    }
                                    if (InvokeLogic.EndInvokeMethod != null)
                                    {
                                        InvokeLogic.EndInvokeMethod.Invoke(null, new object[] { this, methodName });
                                    }
                                    #endregion
                                    //if (InvokeLogic.DocRecord != null)
                                    //{
                                    //    InvokeLogic.DocRecord.Invoke(null, new object[] { this, methodName });
                                    //}
                                }
                            }
                        }
                        #endregion
                    }
                }
                if (string.IsNullOrEmpty(context.Response.Charset))
                {
                    context.Response.Charset = "utf-8";
                }
                if (View != null)
                {
                    context.Response.Write(View.OutXml);
                }
                else if (apiResult.Length > 0)
                {
                    string outResult = apiResult.ToString();
                    if (string.IsNullOrEmpty(context.Response.ContentType))
                    {
                        context.Response.ContentType = "text/html";
                    }
                    if (context.Response.ContentType == "text/html")
                    {
                        if (apiResult[0] == '{' && apiResult[apiResult.Length - 1] == '}')
                        {
                            context.Response.ContentType = "application/json";
                        }
                        else if (outResult.StartsWith("<?xml") && apiResult[apiResult.Length - 1] == '>')
                        {
                            context.Response.ContentType = "application/xml";
                        }
                    }
                    context.Response.Write(outResult);
                }
            }
            catch (System.Threading.ThreadAbortException)
            {
                return;
            }
            catch (Exception err)
            {
                string errMssg = err.InnerException != null ? err.InnerException.Message : err.Message;
                WriteLog(errMssg);
                if (View == null)
                {
                    errMssg = JsonHelper.OutResult(false, errMssg);
                }
                context.Response.Write(errMssg);
            }
        }
Esempio n. 23
0
        public void ProcessRequest(HttpContext context)
        {
            this.context = context;
            try
            {
                Type     t          = _ControllerType = this.GetType();
                string[] items      = QueryTool.GetLocalPath().Trim('/').Split('/');
                string   methodName = string.Empty;
                switch (RouteConfig.RouteMode)
                {
                case 0:
                    methodName = items[0];
                    break;

                case 1:
                    if (items.Length > 1)
                    {
                        methodName = items[1];
                    }
                    break;

                case 2:
                    if (items.Length > 2)
                    {
                        methodName = items[2];
                    }
                    break;
                }
                bool isGoOn = true;
                if (InvokeLogic.BeforeInvokeMethod != null)
                {
                    isGoOn = Convert.ToBoolean(InvokeLogic.BeforeInvokeMethod.Invoke(null, new object[] { this, methodName }));
                }
                if (isGoOn)
                {
                    char[]     attrFlags;
                    MethodInfo method = InvokeLogic.GetMethod(t, methodName, out attrFlags);
                    if (method != null)
                    {
                        if (attrFlags[0] == '1')
                        {
                            #region CheckToken
                            MethodInfo checkToken = InvokeLogic.GetMethod(t, InvokeLogic.CheckToken);
                            if (checkToken != null && checkToken.Name == InvokeLogic.CheckToken)
                            {
                                isGoOn = Convert.ToBoolean(checkToken.Invoke(this, null));
                            }
                            else if (InvokeLogic.CheckTokenMethod != null)
                            {
                                isGoOn = Convert.ToBoolean(InvokeLogic.CheckTokenMethod.Invoke(null, new object[] { this, methodName }));
                            }
                            #endregion
                        }
                        if (isGoOn && attrFlags[1] != attrFlags[2])//配置了HttpGet或HttpPost
                        {
                            if (attrFlags[1] == '1' && !IsHttpGet)
                            {
                                isGoOn = false;
                                Write("Only support HttpGet!", false);
                            }
                            else if (attrFlags[2] == '1' && !IsHttpPost)
                            {
                                isGoOn = false;
                                Write("Only support HttpPost!", false);
                            }
                        }
                        if (isGoOn)
                        {
                            #region Method Invoke
                            _Action = method.Name;
                            BeforeInvoke(method.Name);
                            if (!CancelLoadHtml)
                            {
                                _View = ViewEngine.Create(t.Name, method.Name);
                            }
                            if (!CancelInvoke)
                            {
                                method.Invoke(this, null);
                                if (IsHttpPost)
                                {
                                    string name = GetBtnName();
                                    if (!string.IsNullOrEmpty(name))
                                    {
                                        MethodInfo postBtnMethod = InvokeLogic.GetMethod(t, name);
                                        if (postBtnMethod != null && postBtnMethod.Name != InvokeLogic.Default)
                                        {
                                            postBtnMethod.Invoke(this, null);
                                        }
                                    }
                                }
                                if (!CancelInvoke)
                                {
                                    EndInvoke(method.Name);
                                }
                            }
                            #endregion
                        }
                    }
                }

                if (View != null)
                {
                    context.Response.Write(View.OutXml);
                }
                else if (apiResult.Length > 0)
                {
                    context.Response.Write(apiResult.ToString());
                }
            }
            catch (System.Threading.ThreadAbortException)
            {
                return;
            }
            catch (Exception err)
            {
                string errorMsg = string.Empty;
                if (err.InnerException != null)
                {
                    errorMsg = string.Format("异常信息:{0}" + Environment.NewLine + "堆栈信息:{1}。"
                                             , err.InnerException.Message
                                             , err.InnerException.StackTrace);
                }
                else
                {
                    errorMsg = string.Format("异常信息:{0}" + Environment.NewLine + "堆栈信息:{1}。"
                                             , err.Message,
                                             err.StackTrace);
                }

                WriteError(errorMsg);
                if (AppSettings.IsDevMode)//开发者模式
                {
                    context.Response.Write(errorMsg);
                }
                else
                {
                    context.Response.Write(err.Message);
                }
            }
            if (string.IsNullOrEmpty(context.Response.Charset))
            {
                context.Response.Charset = "utf-8";
            }
        }
Esempio n. 24
0
        public void ProcessRequest(HttpContext context)
        {
            this.context = context;
            try
            {
                Type     t          = _ControllerType = this.GetType();
                string[] items      = QueryTool.GetLocalPath().Trim('/').Split('/');
                string   methodName = string.Empty;
                switch (RouteConfig.RouteMode)
                {
                case 0:
                    methodName = items[0];
                    break;

                case 1:
                    if (items.Length > 1)
                    {
                        methodName = items[1];
                    }
                    break;

                case 2:
                    if (items.Length > 2)
                    {
                        methodName = items[2];
                    }
                    break;
                }
                MethodInfo method = InvokeLogic.GetMethod(t, methodName);
                if (method != null)
                {
                    _Action = method.Name;
                    BeforeInvoke(method.Name);
                    if (!CancelLoadHtml)
                    {
                        _View = ViewEngine.Create(t.Name, method.Name);
                    }
                    //#if DEBUG
                    //                    string text = "Invoke " + t.FullName + "." + Action + "(" + Para + ")<hr />";
                    //                    if (_View != null)
                    //                    {
                    //                        _View.AppendNode(_View.GetList("body")[0], _View.CreateNode("div", text), 0);
                    //                    }
                    //                    else
                    //                    {
                    //                        System.Web.HttpContext.Current.Response.Write(text);
                    //                    }
                    //#endif
                    if (!CancelInvoke)
                    {
                        method.Invoke(this, null);
                        if (IsHttpPost)
                        {
                            string name = GetBtnName();
                            if (!string.IsNullOrEmpty(name))
                            {
                                MethodInfo postBtnMethod = InvokeLogic.GetMethod(t, name);
                                if (postBtnMethod != null && postBtnMethod.Name != InvokeLogic.Default)
                                {
                                    postBtnMethod.Invoke(this, null);
                                }
                            }
                        }
                        if (!CancelInvoke)
                        {
                            EndInvoke(method.Name);
                        }
                    }
                    if (View != null)
                    {
                        context.Response.Write(View.OutXml);
                    }
                    else if (apiResult.Length > 0)
                    {
                        context.Response.Write(apiResult.ToString());
                    }
                }
            }
            catch (System.Threading.ThreadAbortException)
            {
                return;
            }
            catch (Exception err)
            {
                WriteError(err.Message);
                context.Response.Write(err.Message);
            }

            context.Response.End();
        }
Esempio n. 25
0
            /// <summary>
            /// 网关代理转发方法
            /// </summary>
            internal static bool Proxy(HttpContext context, bool isServerCall)
            {
                if ((isServerCall && !Server.IsServer) || (!isServerCall && !Client.IsClient))
                {
                    return(false);
                }
                List <HostInfo> infoList = new List <HostInfo>();
                string          module   = string.Empty;
                IPAddress       iPAddress;
                List <HostInfo> domainList = null;

                if (context.Request.Url.Host != "localhost" && !IPAddress.TryParse(context.Request.Url.Host, out iPAddress))
                {
                    module     = context.Request.Url.Host;//域名转发优先。
                    domainList = isServerCall ? MicroService.Server.GetHostList(module) : MicroService.Client.GetHostList(module);
                    if (domainList == null || domainList.Count == 0)
                    {
                        return(false);
                    }
                }

                if (context.Request.Url.LocalPath == "/")
                {
                    module = QueryTool.GetDefaultUrl().TrimStart('/').Split('/')[0];
                }
                else
                {
                    module = context.Request.Url.LocalPath.TrimStart('/').Split('/')[0];
                }
                List <HostInfo> moduleList = isServerCall ? MicroService.Server.GetHostList(module) : MicroService.Client.GetHostList(module);

                if (domainList == null || domainList.Count == 0)
                {
                    infoList = moduleList;
                }
                else if (moduleList == null || moduleList.Count == 0)
                {
                    infoList = domainList;
                }
                else
                {
                    foreach (var item in domainList)//过滤掉不在域名下的主机
                    {
                        foreach (var keyValue in moduleList)
                        {
                            if (item.Host == keyValue.Host)
                            {
                                infoList.Add(item);
                                break;
                            }
                        }
                    }
                }

                if (infoList == null || infoList.Count == 0)
                {
                    return(false);
                }
                else
                {
                    int      max         = 3;//最多循环3个节点,避免长时间循环卡机。
                    bool     isRegCenter = Server.IsRegCenterOfMaster;
                    HostInfo firstInfo   = infoList[0];
                    if (firstInfo.CallIndex >= infoList.Count)
                    {
                        firstInfo.CallIndex = 0;//处理节点移除后,CallIndex最大值的问题。
                    }
                    for (int i = 0; i < infoList.Count; i++)
                    {
                        int callIndex = firstInfo.CallIndex + i;
                        if (callIndex >= infoList.Count)
                        {
                            callIndex = callIndex - infoList.Count;
                        }
                        HostInfo info = infoList[callIndex];

                        if (info.Version < 0 || (info.CallTime > DateTime.Now && infoList.Count > 0) || (isRegCenter && info.RegTime < DateTime.Now.AddSeconds(-10))) //正常5-10秒注册1次。
                        {
                            continue;                                                                                                                                 //已经断开服务的。
                        }

                        if (Proxy(context, info.Host, isServerCall))
                        {
                            firstInfo.CallIndex = callIndex + 1;//指向下一个。
                            return(true);
                        }
                        else
                        {
                            info.CallTime = DateTime.Now.AddSeconds(10);//网络异常的,延时10s检测。
                            max--;
                            if (max == 0)
                            {
                                return(false);
                            }
                        }
                    }
                    return(false);
                }
            }