示例#1
0
        /// <summary>
        /// Action执行之前执行
        /// </summary>
        /// <param name="filterContext"></param>
        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            ICheckSignBusiness checkSignBusiness = AutofacHelper.GetService <ICheckSignBusiness>();

            //若为本地测试,则不需要校验
            if (GlobalSwitch.RunModel == RunModel.LocalTest)
            {
                return;
            }

            //判断是否需要签名
            List <string> attrList = FilterHelper.GetFilterList(filterContext);
            bool          needSign = attrList.Contains(typeof(CheckSignAttribute).FullName) && !attrList.Contains(typeof(IgnoreSignAttribute).FullName);

            //不需要签名
            if (!needSign)
            {
                return;
            }

            //需要签名
            var checkSignRes = checkSignBusiness.IsSecurity(filterContext.HttpContext);

            if (!checkSignRes.Success)
            {
                filterContext.Result = new ContentResult()
                {
                    Content = checkSignRes.ToJson()
                };
            }
        }
        /// <summary>
        /// Action执行之前执行
        /// </summary>
        /// <param name="filterContext">过滤器上下文</param>
        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            IOperator  Operator  = AutofacHelper.GetService <IOperator>();
            IBusHelper BusHelper = AutofacHelper.GetService <IBusHelper>();

            var request = filterContext.HttpContext.Request;

            try
            {
                //若为本地测试,则不需要登录
                if (GlobalSwitch.RunModel == RunModel.LocalTest)
                {
                    return;
                }
                //判断是否需要登录
                List <string> attrList  = FilterHelper.GetFilterList(filterContext);
                bool          needLogin = attrList.Contains(typeof(CheckLoginAttribute).FullName) && !attrList.Contains(typeof(IgnoreLoginAttribute).FullName);

                //转到登录
                if (needLogin && !Operator.Logged())
                {
                    RedirectToLogin();
                }
            }
            catch (Exception ex)
            {
                BusHelper.HandleException(ex);
                RedirectToLogin();
            }

            void RedirectToLogin()
            {
                if (request.IsAjaxRequest())
                {
                    filterContext.Result = new ContentResult
                    {
                        Content = new AjaxResult {
                            Success = false, ErrorCode = 1, Msg = "未登录"
                        }.ToJson(),
                        ContentType = "application/json;charset=UTF-8"
                    };
                }
                else
                {
                    UrlHelper urlHelper = new UrlHelper(filterContext);
                    string    loginUrl  = urlHelper.Content("~/Home/Login");
                    string    script    = $@"    
<html>
    <script>
        top.location.href = '{loginUrl}';
    </script>
</html>
";
                    filterContext.Result = new ContentResult {
                        Content = script, ContentType = "text/html"
                    };
                }
            }
        }
        public static string MapPath(this HttpContext httpContext, string virtualPath)
        {
            UrlHelper urlHelper = new UrlHelper(AutofacHelper.GetService <IActionContextAccessor>().ActionContext);

            virtualPath = urlHelper.Content(virtualPath);

            return($"{Path.Combine(new List<string> { GlobalSwitch.WebRootPath }.Concat(virtualPath.Split('/')).ToArray())}");
        }
示例#4
0
        public async Task TestMethod1()
        {
            var roleService = AutofacHelper.GetService <ISysRolesService>();
            var dataList    = await roleService.GetModelsAsync(new SysRolesRequestModel()
            {
            });

            Assert.IsTrue(dataList.ToList().Count > 0);
        }
        /// <summary>
        /// Action执行之前执行
        /// </summary>
        /// <param name="filterContext">过滤器上下文</param>
        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            IPermissionManage    PermissionManage    = AutofacHelper.GetService <IPermissionManage>();
            IUrlPermissionManage UrlPermissionManage = AutofacHelper.GetService <IUrlPermissionManage>();

            //若为本地测试,则不需要校验
            if (GlobalSwitch.RunModel == RunModel.LocalTest)
            {
                return;
            }
            AjaxResult res = new AjaxResult();
            //判断是否需要校验
            List <string> attrList  = FilterHelper.GetFilterList(filterContext);
            bool          needCheck = attrList.Contains(typeof(CheckAppIdPermissionAttribute).FullName) && !attrList.Contains(typeof(IgnoreAppIdPermissionAttribute).FullName);

            if (!needCheck)
            {
                return;
            }

            var allRequestParams = HttpHelper.GetAllRequestParams(filterContext.HttpContext);

            if (!allRequestParams.ContainsKey("appId"))
            {
                res.Success          = false;
                res.Msg              = "缺少appId参数!";
                filterContext.Result = new ContentResult {
                    Content = res.ToJson()
                };
            }
            string appId             = allRequestParams["appId"]?.ToString();
            var    allUrlPermissions = UrlPermissionManage.GetAllUrlPermissions();
            string requestUrl        = filterContext.HttpContext.Request.Path;
            var    thePermission     = allUrlPermissions.Where(x => requestUrl.Contains(x.Url.ToLower())).FirstOrDefault();

            if (thePermission == null)
            {
                return;
            }
            string needPermission = thePermission.PermissionValue;
            bool   hasPermission  = PermissionManage.GetAppIdPermissionValues(appId).Any(x => x.ToLower() == needPermission.ToLower());

            if (hasPermission)
            {
                return;
            }
            else
            {
                res.Success          = false;
                res.Msg              = "权限不足!访问失败!";
                filterContext.Result = new ContentResult {
                    Content = res.ToJson()
                };
            }
        }
示例#6
0
 public Client()
 {
     Config   = AutofacHelper.GetService <SystemConfig>();
     Protocol = JTTProtocolExtension.GetProtocol <JTT809Protocol>(Config.JTTConfigFilePath, Config.JTTVersion);
     Protocol.Initialization();
     Protocol.DefaultVersionFlag      = Config.JTTVersionFlag;
     Protocol.Structures              = Config.Structures;
     Protocol.InternalEntitysMappings = Config.InternalEntitysMappings;
     Protocol.DataMappings            = Config.DataMappings;
     Filter = Protocol.GetFilter();
 }
示例#7
0
 public void StartJob()
 {
     try
     {
         var cusService = AutofacHelper.GetService <ICrm_CustomerService>();
         var s          = cusService.GetTheData("039ed57b565cc-6b8ea799-9345-4e1f-84e1-fb3feee192d9");
         Console.WriteLine("任务执行中");
     }
     catch (Exception ex)
     {
     }
 }
示例#8
0
        /// <summary>
        /// 获取绝对路径
        /// </summary>
        /// <param name="virtualPath">虚拟路径</param>
        /// <returns></returns>
        public static string GetAbsolutePath(string virtualPath)
        {
            string path = virtualPath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);

            if (path[0] == '~')
            {
                path = path.Remove(0, 2);
            }
            string rootPath = AutofacHelper.GetService <IHostingEnvironment>().WebRootPath;

            return(Path.Combine(rootPath, path));
        }
示例#9
0
        /// <summary>
        /// 获取Url
        /// </summary>
        /// <param name="virtualUrl">虚拟Url</param>
        /// <returns></returns>
        public static string GetUrl(string virtualUrl)
        {
            if (!virtualUrl.IsNullOrEmpty())
            {
                UrlHelper urlHelper = new UrlHelper(AutofacHelper.GetService <IActionContextAccessor>().ActionContext);

                return(urlHelper.Content(virtualUrl));
            }
            else
            {
                return(null);
            }
        }
        public static IServiceCollection RegisterJTTServer(this IServiceCollection services, SystemConfig config)
        {
            services.AddJTT(options =>
            {
                options.ProtocolOptions = new SuperSocket.JTT.Server.Model.JTTProtocolOptions
                {
                    Version = config.JTTVersion,
                    JTTCustomAssemblyName = Assembly.GetExecutingAssembly().GetName().Name,
                    ConfigFilePath        = config.JTTConfigFilePath,

                    Structures              = config.Structures,
                    DataMappings            = config.DataMappings,
                    InternalEntitysMappings = config.InternalEntitysMappings,
                };

                options.ServerOptions = new SuperSocket.JTT.Server.Model.JTTServerOptions
                {
                    Name    = config.ServerName,
                    IP      = config.ServerIP,
                    Port    = config.ServerPort,
                    BackLog = config.ServerBackLog,

                    UseUdp = true,

                    PackageHandler = PackageHandler.Handler,
                    OnConnected    = SessionHandler.OnConnected,
                    OnClosed       = SessionHandler.OnClosed,

                    InProcSessionContainer = true,

                    ConfigureServices = (context, services, protocol) =>
                    {
                    },
                    ConfigureAppConfiguration = (hostCtx, configApp, protocol) =>
                    {
                    }
                };

                options.LoggingOptions = new SuperSocket.JTT.Server.Model.JTTLoggingOptions
                {
                    AddConsole = true,
                    AddDebug   = true,
                    Provider   = AutofacHelper.GetService <ILoggerProvider>()
                };
            });

            return(services);
        }
        public ActionResult SaveFile()
        {
            string rootPath = AutofacHelper.GetService <IHostingEnvironment>().WebRootPath;

            string path = Path.Combine(rootPath, "Upload");

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            string file = Path.Combine(path, "text.txt");

            System.IO.File.WriteAllText(file, "测试", Encoding.UTF8);

            return(Success());
        }
        public void OnException(ExceptionContext context)
        {
            IBusHelper BusHelper = AutofacHelper.GetService <IBusHelper>();

            var ex = context.Exception;

            BusHelper.HandleException(ex);

            context.Result = new ContentResult
            {
                Content = new AjaxResult {
                    Success = false, Msg = ex.Message
                }.ToJson(),
                ContentType = "application/json; charset=utf-8",
            };
        }
示例#13
0
        //[CheckSign]
        public ActionResult RequestTest()
        {
            var       bus  = AutofacHelper.GetService <IBase_UserBusiness>();
            var       db   = DbFactory.GetRepository();
            Base_User data = new Base_User
            {
                Id       = IdHelper.GetId(),
                UserName = IdHelper.GetId()
            };

            db.Insert(data);
            db.Update(data);
            db.GetIQueryable <Base_User>().FirstOrDefault();
            db.Delete(data);
            //db.Dispose();

            return(Success(""));
        }
示例#14
0
        /// <summary>
        /// Action执行之前执行
        /// </summary>
        /// <param name="filterContext">过滤器上下文</param>
        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            IPermissionManage    PermissionManage    = AutofacHelper.GetService <IPermissionManage>();
            IUrlPermissionManage UrlPermissionManage = AutofacHelper.GetService <IUrlPermissionManage>();

            //若为本地测试,则不需要校验
            if (GlobalSwitch.RunModel == RunModel.LocalTest)
            {
                return;
            }

            //判断是否需要校验
            if (filterContext.ContainsFilter <IgnoreUrlPermissionAttribute>())
            {
                return;
            }

            var    allUrlPermissions = UrlPermissionManage.GetAllUrlPermissions();
            string requestUrl        = filterContext.HttpContext.Request.Path;
            var    thePermission     = allUrlPermissions.Where(x => requestUrl.ToLower().Contains(x.Url.ToLower())).FirstOrDefault();

            if (thePermission == null)
            {
                return;
            }
            string needPermission = thePermission.PermissionValue;
            bool   hasPermission  = PermissionManage.GetOperatorPermissionValues().Any(x => x.ToLower() == needPermission.ToLower());

            if (hasPermission)
            {
                return;
            }
            else
            {
                AjaxResult res = new AjaxResult
                {
                    Success = false,
                    Msg     = "权限不足!无法访问!"
                };
                filterContext.Result = new ContentResult {
                    Content = res.ToJson(), ContentType = "application/json;charset=utf-8"
                };
            }
        }
示例#15
0
        /// <summary>
        /// 压力测试
        /// </summary>
        /// <returns></returns>
        public ActionResult PressTest()
        {
            var           bus  = AutofacHelper.GetService <IBase_UserBusiness>();
            var           db   = DbFactory.GetRepository();
            Base_UnitTest data = new Base_UnitTest
            {
                Id       = Guid.NewGuid().ToString(),
                UserId   = Guid.NewGuid().ToString(),
                Age      = 10,
                UserName = Guid.NewGuid().ToString()
            };

            db.Insert(data);
            db.Update(data);
            db.GetIQueryable <Base_UnitTest>().FirstOrDefault();
            db.Delete(data);

            return(Success(""));
        }
示例#16
0
        static BuildCodeBusiness()
        {
            var projectPath = AutofacHelper.GetService <IHostingEnvironment>().ContentRootPath;

            _solutionPath = Directory.GetParent(projectPath).ToString();
        }
示例#17
0
 static RapidDevelopmentBusiness()
 {
     _contentRootPath = AutofacHelper.GetService <IHostingEnvironment>().ContentRootPath;
 }
        private static List <Menu> InitAllMenu()
        {
            Action <Menu, XElement> SetMenuProperty = (menu, element) =>
            {
                List <string> exceptProperties = new List <string> {
                    "Id", "IsShow"
                };
                var types = menu.GetType().GetProperties().Where(x => !exceptProperties.Contains(x.Name)).ToList();
                types.ForEach(aProperty =>
                {
                    aProperty.SetValue(menu, element.Attribute(aProperty.Name)?.Value);
                });
            };

            string      filePath  = _configFile;
            XElement    xe        = XElement.Load(filePath);
            List <Menu> menus     = new List <Menu>();
            int         menuIndex = 10000;

            xe.Elements("FirstMenu")?.ForEach(aElement1 =>
            {
                menuIndex++;
                Menu newMenu1 = new Menu()
                {
                    Id = menuIndex
                };
                menus.Add(newMenu1);
                SetMenuProperty(newMenu1, aElement1);
                newMenu1.SubMenus = new List <Menu>();
                aElement1.Elements("SecondMenu")?.ForEach(aElement2 =>
                {
                    menuIndex++;
                    Menu newMenu2 = new Menu()
                    {
                        Id = menuIndex
                    };
                    newMenu1.SubMenus.Add(newMenu2);
                    SetMenuProperty(newMenu2, aElement2);
                    newMenu2.SubMenus = new List <Menu>();

                    aElement2.Elements("ThirdMenu")?.ForEach(aElement3 =>
                    {
                        menuIndex++;
                        Menu newMenu3 = new Menu()
                        {
                            Id = menuIndex
                        };
                        newMenu2.SubMenus.Add(newMenu3);
                        SetMenuProperty(newMenu3, aElement3);
                        if (!newMenu3.Url.IsNullOrEmpty())
                        {
                            UrlHelper urlHelper = new UrlHelper(AutofacHelper.GetService <IActionContextAccessor>().ActionContext);
                            newMenu3.Url        = urlHelper.Content(newMenu3.Url);
                        }
                    });
                });
            });
            Base_MenuBusiness menuService = new Base_MenuBusiness();

            List <Menu> allMenu = menuService.GetList();

            if (allMenu.Count > 0)
            {
                List <Menu> firstMenu = allMenu.Where(m => m.MenuLevel == "1").ToList();
                if (firstMenu.Count > 0)
                {
                    firstMenu.ForEach(m1 =>
                    {
                        m1.SubMenus = allMenu.Where(m => m.ParentMenuId == m1.Id).ToList();

                        if (m1.SubMenus.Count > 0)
                        {
                            m1.SubMenus.ForEach(m2 =>
                            {
                                List <Menu> sub2 = allMenu.Where(m => m.ParentMenuId == m2.Id).ToList();
                                m2.SubMenus      = sub2;
                            });
                        }
                        menus.Add(m1);
                    });
                }
            }

            if (GlobalSwitch.RunModel == RunModel.LocalTest)
            {
                Menu newMenu1 = new Menu
                {
                    Id       = menuIndex++,
                    Name     = "开发",
                    Icon     = "icon_menu_prod",
                    SubMenus = new List <Menu>()
                };
                menus.Add(newMenu1);
                Menu newMenu1_1 = new Menu
                {
                    Id       = menuIndex++,
                    Name     = "快速开发",
                    SubMenus = new List <Menu>()
                };
                newMenu1.SubMenus.Add(newMenu1_1);
                Menu newMenu1_1_1 = new Menu
                {
                    Id   = menuIndex++,
                    Name = "代码生成",
                    Url  = GetUrl("~/Base_SysManage/RapidDevelopment/Index")
                };
                newMenu1_1.SubMenus.Add(newMenu1_1_1);

                Menu newMenu1_1_2 = new Menu
                {
                    Id   = menuIndex++,
                    Name = "数据库连接管理",
                    Url  = GetUrl("~/Base_SysManage/Base_DatabaseLink/Index")
                };
                newMenu1_1.SubMenus.Add(newMenu1_1_2);

                Menu newMenu1_1_3 = new Menu
                {
                    Id   = menuIndex++,
                    Name = "UEditor Demo",
                    Url  = GetUrl("~/Demo/UMEditor")
                };
                newMenu1_1.SubMenus.Add(newMenu1_1_3);

                Menu newMenu1_1_4 = new Menu
                {
                    Id   = menuIndex++,
                    Name = "文件上传Demo",
                    Url  = GetUrl("~/Demo/UploadFileIndex")
                };
                newMenu1_1.SubMenus.Add(newMenu1_1_4);

                Menu newMenu1_1_5 = new Menu
                {
                    Id   = menuIndex++,
                    Name = "菜单权限管理",
                    Url  = GetUrl("~/Base_SysManage/Base_Menu/Index")
                };
                newMenu1_1.SubMenus.Add(newMenu1_1_5);
            }

            return(menus);
        }
        private static string GetUrl(string virtualUrl)
        {
            UrlHelper urlHelper = new UrlHelper(AutofacHelper.GetService <IActionContextAccessor>().ActionContext);

            return(urlHelper.Content(virtualUrl));
        }
示例#20
0
        private static void InitAllMenu()
        {
            Action <Menu, XElement> SetMenuProperty = (menu, element) =>
            {
                List <string> exceptProperties = new List <string> {
                    "Id", "IsShow"
                };
                menu.GetType().GetProperties().Where(x => !exceptProperties.Contains(x.Name)).ForEach(aProperty =>
                {
                    aProperty.SetValue(menu, element.Attribute(aProperty.Name)?.Value);
                });
            };

            string      filePath = _configFile;
            XElement    xe       = XElement.Load(filePath);
            List <Menu> menus    = new List <Menu>();

            xe.Elements("FirstMenu")?.ForEach(aElement1 =>
            {
                Menu newMenu1 = new Menu();
                menus.Add(newMenu1);
                SetMenuProperty(newMenu1, aElement1);
                newMenu1.SubMenus = new List <Menu>();
                aElement1.Elements("SecondMenu")?.ForEach(aElement2 =>
                {
                    Menu newMenu2 = new Menu();
                    newMenu1.SubMenus.Add(newMenu2);
                    SetMenuProperty(newMenu2, aElement2);
                    newMenu2.SubMenus = new List <Menu>();

                    aElement2.Elements("ThirdMenu")?.ForEach(aElement3 =>
                    {
                        Menu newMenu3 = new Menu();
                        newMenu2.SubMenus.Add(newMenu3);
                        SetMenuProperty(newMenu3, aElement3);
                        if (!newMenu3.Url.IsNullOrEmpty())
                        {
                            UrlHelper urlHelper = new UrlHelper(AutofacHelper.GetService <IActionContextAccessor>().ActionContext);
                            newMenu3.Url        = urlHelper.Content(newMenu3.Url);
                        }
                    });
                });
            });

            if (GlobalSwitch.RunModel == RunModel.LocalTest)
            {
                Menu newMenu1 = new Menu
                {
                    Name     = "开发",
                    Icon     = "icon_menu_prod",
                    SubMenus = new List <Menu>()
                };
                menus.Add(newMenu1);
                Menu newMenu2 = new Menu
                {
                    Name     = "快速开发",
                    SubMenus = new List <Menu>()
                };
                newMenu1.SubMenus.Add(newMenu2);
                Menu newMenu3_1 = new Menu
                {
                    Name = "代码生成",
                    Url  = GetUrl("~/Base_SysManage/RapidDevelopment/Index")
                };
                newMenu2.SubMenus.Add(newMenu3_1);

                Menu newMenu3_2 = new Menu
                {
                    Name = "数据库连接管理",
                    Url  = GetUrl("~/Base_SysManage/Base_DatabaseLink/Index")
                };
                newMenu2.SubMenus.Add(newMenu3_2);
            }

            _allMenu = menus;
        }
示例#21
0
        static async Task Main(string[] args)
        {
            "系统启动中.".ConsoleWrite();
            "正在读取配置.".ConsoleWrite();

            var config = new ConfigHelper()
                         .GetModel <SystemConfig>("SystemConfig");

            if (config == null)
            {
                "系统配置读取失败, appsettings.json Section: SystemConfig.".ConsoleWrite();
                return;
            }

            Console.Title = config.ProjectName;

            $"使用{config.JTTVersion}协议.".ConsoleWrite();

            var services = new ServiceCollection();

            services.AddSingleton(config)
            .AddLogging()
            .RegisterNLog(config)
            .RegisterJTTServer(config);

            "已应用Autofac容器".ConsoleWrite();
            AutofacHelper.Container = new AutofacServiceProviderFactory().CreateBuilder(services).Build();

            var jttProvider = AutofacHelper.GetService <IJTTProvider>();

            "正在构建主机".ConsoleWrite();

            var jttHostBuilder = jttProvider.GetJTTServerHostBuilder();

            var jttHost = jttHostBuilder.Build();

            PackageHandler.SetUp(jttHost.Services);

            "应用程序已启动".ConsoleWrite();

            await jttHost.RunAsync();

            CancellationToken cancelToken = new CancellationToken(false);
            await jttHost.RunAsync(cancelToken)
            .ContinueWith(task =>
            {
                try
                {
                    cancelToken.ThrowIfCancellationRequested();
                }
                catch (Exception ex)
                {
                    Logger.Log(
                        NLog.LogLevel.Error,
                        LogType.系统异常,
                        $"应用程序关闭时时异常.",
                        null,
                        ex);
                }
            });
        }
示例#22
0
        /// <summary>
        /// Action执行之前执行
        /// </summary>
        /// <param name="filterContext"></param>
        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            IBase_AppSecretBusiness appSecretBus = AutofacHelper.GetService <IBase_AppSecretBusiness>();

            //若为本地测试,则不需要校验
            if (GlobalSwitch.RunModel == RunModel.LocalTest)
            {
                return;
            }

            //判断是否需要签名
            if (filterContext.ContainsFilter <IgnoreSignAttribute>())
            {
                return;
            }

            var    request = filterContext.HttpContext.Request;
            string appId   = request.Headers["appId"].ToString();

            if (appId.IsNullOrEmpty())
            {
                ReturnError("缺少header:appId");
                return;
            }
            string time = request.Headers["time"].ToString();

            if (time.IsNullOrEmpty())
            {
                ReturnError("缺少header:time");
                return;
            }
            if (time.ToDateTime() < DateTime.Now.AddMinutes(-5) || time.ToDateTime() > DateTime.Now.AddMinutes(5))
            {
                ReturnError("time过期");
                return;
            }

            string guid = request.Headers["guid"].ToString();

            if (guid.IsNullOrEmpty())
            {
                ReturnError("缺少header:guid");
                return;
            }

            string guidKey = $"{GlobalSwitch.ProjectName}_apiGuid_{guid}";

            if (CacheHelper.Cache.GetCache(guidKey).IsNullOrEmpty())
            {
                CacheHelper.Cache.SetCache(guidKey, "1", new TimeSpan(0, 10, 0));
            }
            else
            {
                ReturnError("禁止重复调用!");
                return;
            }

            string body = request.Body.ReadToString();

            string sign = request.Headers["sign"].ToString();

            if (sign.IsNullOrEmpty())
            {
                ReturnError("缺少header:sign");
                return;
            }

            string appSecret = appSecretBus.GetAppSecret(appId);

            if (appSecret.IsNullOrEmpty())
            {
                ReturnError("header:appId无效");
                return;
            }

            string newSign = HttpHelper.BuildApiSign(appId, appSecret, guid, time.ToDateTime(), body);

            if (sign != newSign)
            {
                ReturnError("header:sign签名错误");
                return;
            }

            void ReturnError(string msg)
            {
                AjaxResult res = new AjaxResult
                {
                    Success = false,
                    Msg     = msg
                };

                filterContext.Result = new ContentResult {
                    Content = res.ToJson(), ContentType = "application/json;charset=utf-8"
                };
            }
        }