protected override void ReInitVM() { var data = DC.Set <FrameworkMenu>().ToList(); var topMenu = data.Where(x => x.ParentId == null).ToList().FlatTree(x => x.DisplayOrder); var pids = Entity.GetAllChildrenIDs(DC); AllParents = topMenu.Where(x => x.ID != Entity.ID && !pids.Contains(x.ID) && x.FolderOnly == true).ToList().ToListItems(y => y.PageName, x => x.ID); var modules = GlobalServices.GetRequiredService <GlobalData>().AllModule; var m = modules.Where(x => x.NameSpace != "WalkingTec.Mvvm.Admin.Api").ToList(); List <FrameworkModule> toremove = new List <FrameworkModule>(); foreach (var item in m) { var f = modules.Where(x => x.ClassName == item.ClassName && x.Area?.AreaName == item.Area?.AreaName).FirstOrDefault(); if (f?.IgnorePrivillege == true) { toremove.Add(item); } } toremove.ForEach(x => m.Remove(x)); AllModules = m.ToListItems(y => y.ModuleName, y => y.FullName); if (string.IsNullOrEmpty(SelectedModule) == false) { var mm = modules.Where(x => x.FullName == SelectedModule).SelectMany(x => x.Actions).Where(x => x.MethodName != "Index" && x.IgnorePrivillege == false).ToList(); AllActions = mm.ToListItems(y => y.ActionName, y => y.Url); } }
public void DoLog(string msg, ActionLogTypesEnum logtype = ActionLogTypesEnum.Debug) { var log = this.Log.GetActionLog(); log.LogType = logtype; log.ActionTime = DateTime.Now; log.Remark = msg; LogLevel ll = LogLevel.Information; switch (logtype) { case ActionLogTypesEnum.Normal: ll = LogLevel.Information; break; case ActionLogTypesEnum.Exception: ll = LogLevel.Error; break; case ActionLogTypesEnum.Debug: ll = LogLevel.Debug; break; default: break; } GlobalServices.GetRequiredService<ILogger<ActionLog>>().Log<ActionLog>(ll, new EventId(), log, null, (a, b) => { return $@" ===WTM Log=== 内容:{a.Remark} 地址:{a.ActionUrl} 时间:{a.ActionTime} ===WTM Log=== "; }); }
/// <summary> /// 查询结果 /// </summary> public override IOrderedQueryable <FrameworkMenu_ListView> GetSearchQuery() { var modules = GlobalServices.GetRequiredService <GlobalData>().AllModule; var ms = modules.Where(x => x.IsApi == true).Select(x => "/" + x.ClassName); var data = DC.Set <FrameworkMenu>().ToList(); var topdata = data.Where(x => x.ParentId == null).ToList().FlatTree(x => x.DisplayOrder).Where(x => x.IsInside == false || x.FolderOnly == true || string.IsNullOrEmpty(x.MethodName)).ToList(); int order = 0; var data2 = topdata.Select(x => new FrameworkMenu_ListView { ID = x.ID, PageName = x.PageName, ModuleName = x.ModuleName, ActionName = x.ActionName, ShowOnMenu = x.ShowOnMenu, FolderOnly = x.FolderOnly, IsPublic = x.IsPublic, DisplayOrder = x.DisplayOrder, ExtraOrder = order++, ParentID = x.ParentId, ICon = x.IConId, HasChild = (x.Children != null && x.Children.Count() > 0) ? true : false }).OrderBy(x => x.ExtraOrder).ToList(); foreach (var item in data2) { if (item.ParentID != null) { var p = data2.Where(x => x.ID == item.ParentID).SingleOrDefault(); if (p != null) { if (p.Children == null) { p.Children = new List <FrameworkMenu_ListView>(); } var t = p.Children.ToList(); t.Add(new FrameworkMenu_ListView { ID = item.ID, PageName = item.PageName, ModuleName = item.ModuleName, ActionName = item.ActionName, ShowOnMenu = item.ShowOnMenu, FolderOnly = item.FolderOnly, IsPublic = item.IsPublic, DisplayOrder = item.DisplayOrder, ExtraOrder = order++, ParentID = item.ParentID, ICon = item.ICon, HasChild = (item.Children != null && item.Children.Count() > 0) ? true : false } ); p.Children = t; } } } var toremove = data2.Where(x => x.ParentID != null).ToList(); toremove.ForEach(x => data2.Remove(x)); return(data2.AsQueryable() as IOrderedQueryable <FrameworkMenu_ListView>); }
/// <summary> /// 查询结果 /// </summary> public override IOrderedQueryable <FrameworkAction_ListView> GetSearchQuery() { var newdc = DC as FrameworkContext; var actions = newdc.Set <FrameworkAction>() .Where(x => newdc.BaseFrameworkMenus.Where(y => y.ActionId != null).Select(y => y.ActionId).Distinct().Contains(x.ID) == false) .Select(x => new FrameworkAction_ListView { ID = x.ID, ModuleID = x.ModuleId, ModuleName = x.Module.ModuleName, ActionName = x.ActionName, ClassName = x.Module.ClassName, MethodName = x.MethodName, AreaName = x.Module.Area.AreaName }).ToList(); var modules = GlobalServices.GetRequiredService <GlobalData>().AllModule; List <FrameworkAction_ListView> toremove = new List <FrameworkAction_ListView>(); foreach (var item in actions) { var m = modules.Where(x => x.ClassName == item.ClassName && x.Area?.AreaName == item.AreaName).FirstOrDefault(); var a = m?.Actions.Where(x => x.MethodName == item.MethodName).FirstOrDefault(); if (m?.IgnorePrivillege == true || a?.IgnorePrivillege == true) { toremove.Add(item); } } toremove.ForEach(x => actions.Remove(x)); return(actions.AsQueryable().OrderBy(x => x.AreaName).ThenBy(x => x.ModuleName).ThenBy(x => x.MethodName)); }
private IDataContext CreateDC() { string cs = "default"; var globalIngo = GlobalServices.GetRequiredService <GlobalData>(); return((IDataContext)globalIngo.DataContextCI?.Invoke(new object[] { _configs.ConnectionStrings?.Where(x => x.Key.ToLower() == cs).Select(x => x.Value).FirstOrDefault(), _configs.DbType })); }
public override Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { var baseVM = Vm?.Model as BaseVM; var tempSearchTitleId = Guid.NewGuid().ToNoSplitString(); bool show = false; if (ListVM?.Searcher?.IsExpanded != null) { Expanded = ListVM?.Searcher?.IsExpanded; } if (Expanded != null) { show = Expanded.Value; } else { show = GlobalServices.GetRequiredService <Configs>().UiOptions.SearchPanel.DefaultExpand; } var layuiShow = show ? " layui-show" : string.Empty; output.PreContent.AppendHtml($@" <div class=""layui-collapse"" style=""margin-bottom:5px;"" lay-filter=""{tempSearchTitleId}x""> <div class=""layui-colla-item""> <h2 class=""layui-colla-title"">{Program._localizer["SearchCondition"]} <div style=""text-align:right;margin-top:-43px;"" id=""{tempSearchTitleId}""> <a href=""javascript:void(0)"" class=""layui-btn layui-btn-sm"" id=""{SearchBtnId}""><i class=""layui-icon""></i>{Program._localizer["Search"]}</a> {(!ResetBtn ? string.Empty : $@"<button type=""button"" class=""layui-btn layui-btn-sm"" id=""{ResetBtnId}"">{Program._localizer["Reset"]}</button>")}
public ComboBoxTagHelper() { if (EmptyText == null) { EmptyText = Program._localizer["PleaseSelect"]; } EnableSearch = GlobalServices.GetRequiredService <Configs>().UiOptions.ComboBox.DefaultEnableSearch; }
public JsonResult GetActionsByModelId(string Id) { var modules = GlobalServices.GetRequiredService <GlobalData>().AllModule; var m = modules.Where(x => x.ClassName == Id).SelectMany(x => x.Actions).Where(x => x.MethodName != "Index" && x.IgnorePrivillege == false).ToList(); var AllActions = m.ToListItems(y => y.ActionName, y => y.Url); AllActions.ForEach(x => x.Selected = true); return(Json(AllActions)); }
public TokenService( ILogger <TokenService> logger, IOptions <JwtOptions> jwtOptions ) { _configs = GlobalServices.GetRequiredService <Configs>(); _jwtOptions = jwtOptions.Value; _logger = logger; _dc = CreateDC(); }
protected override void InitVM() { SelectedRolesIDs.AddRange(DC.Set<FunctionPrivilege>().Where(x => x.MenuItemId == Entity.ID && x.RoleId != null && x.Allowed == true).Select(x => x.RoleId.Value).ToList()); var data = DC.Set<FrameworkMenu>().ToList(); var topMenu = data.Where(x => x.ParentId == null).ToList().FlatTree(x=>x.DisplayOrder); var pids = Entity.GetAllChildrenIDs(DC); AllParents = topMenu.Where(x => x.ID != Entity.ID && !pids.Contains(x.ID) && x.FolderOnly == true).ToList().ToListItems(y => y.PageName, x => x.ID); foreach (var p in AllParents) { Guid temp = Guid.Parse(p.Value); var m = topMenu.Where(x => x.ID == temp).SingleOrDefault(); if (m != null && m.ActionId != null) { p.Text = p.Text + "(" + m.ModuleName + ")"; } } var modules = GlobalServices.GetRequiredService<GlobalData>().AllModule; if (ControllerName.Contains("WalkingTec.Mvvm.Mvc.Admin.Controllers")) { var m = DC.Set<FrameworkModule>().Include(x=>x.Area).Where(x => x.NameSpace != "WalkingTec.Mvvm.Admin.Api").ToList(); List<FrameworkModule> toremove = new List<FrameworkModule>(); foreach (var item in m) { var f = modules.Where(x => x.ClassName == item.ClassName && x.Area?.AreaName == item.Area?.AreaName).FirstOrDefault(); if (f?.IgnorePrivillege == true) { toremove.Add(item); } } toremove.ForEach(x => m.Remove(x)); AllModules = m.ToListItems(y => y.ModuleName, y=>y.ID); } if (Entity.ModuleId != null) { var m = DC.Set<FrameworkAction>().Include(x=>x.Module.Area).Where(x => x.ModuleId == Entity.ModuleId && x.MethodName != "Index").ToList(); List<FrameworkAction> toremove = new List<FrameworkAction>(); foreach (var item in m) { var f = modules.Where(x => x.ClassName == item.Module.ClassName && x.Area?.AreaName == item.Module.Area?.AreaName).FirstOrDefault(); var a = f?.Actions.Where(x => x.MethodName == item.MethodName).FirstOrDefault(); if (a?.IgnorePrivillege == true) { toremove.Add(item); } } toremove.ForEach(x => m.Remove(x)); AllActions = m.ToListItems(y => y.ActionName, y => y.ID); SelectedActionIDs = DC.Set<FrameworkMenu>().Where(x => x.ModuleId == this.Entity.ModuleId && x.ActionId != null).Select(x => x.ActionId.Value).ToList(); } }
/// <summary> /// 查询结果 /// </summary> public override IOrderedQueryable <FrameworkAction_ListView> GetSearchQuery() { var newdc = DC as FrameworkContext; List <FrameworkAction_ListView> actions = new List <FrameworkAction_ListView>(); var urls = newdc.BaseFrameworkMenus.Where(y => y.IsInside == true && y.FolderOnly == false).Select(y => y.Url).Distinct().ToList(); if (ControllerName == "WalkingTec.Mvvm.Mvc.Admin.Controllers.FrameworkMenuController") { actions = GlobalServices.GetRequiredService <GlobalData>().AllModule.SelectMany(x => x.Actions) .Where(x => urls.Contains(x.Url) == false) .Select(x => new FrameworkAction_ListView { ID = x.ID, ModuleID = x.ModuleId, ModuleName = x.Module.ModuleName, ActionName = x.ActionName, ClassName = x.Module.ClassName, MethodName = x.MethodName, AreaName = x.Module.Area?.AreaName }).ToList(); } else { actions = GlobalServices.GetRequiredService <GlobalData>().AllModule.SelectMany(x => x.Actions) .Where(x => x.Module.IsApi == true && urls.Contains(x.Url) == false) .Select(x => new FrameworkAction_ListView { ID = x.ID, ModuleID = x.ModuleId, ModuleName = x.Module.ModuleName, ActionName = x.ActionName, ClassName = x.Module.ClassName, MethodName = x.MethodName, AreaName = x.Module.Area?.AreaName }).ToList(); } var modules = GlobalServices.GetRequiredService <GlobalData>().AllModule; List <FrameworkAction_ListView> toremove = new List <FrameworkAction_ListView>(); foreach (var item in actions) { var m = modules.Where(x => x.ClassName == item.ClassName && x.Area?.AreaName == item.AreaName).FirstOrDefault(); var a = m?.Actions.Where(x => x.MethodName == item.MethodName).FirstOrDefault(); if (m?.IgnorePrivillege == true || a?.IgnorePrivillege == true) { toremove.Add(item); } } toremove.ForEach(x => actions.Remove(x)); return(actions.AsQueryable().OrderBy(x => x.AreaName).ThenBy(x => x.ModuleName).ThenBy(x => x.MethodName)); }
protected override void InitVM() { if (!string.IsNullOrEmpty(Entity.ICon)) { var res = Entity.ICon.Split(' '); IconFont = res[0]; IconFontItem = res[1]; } IConSelectItems = !string.IsNullOrEmpty(IconFont) && IconFontsHelper .IconFontDicItems .ContainsKey(IconFont) ? IconFontsHelper .IconFontDicItems[IconFont] .Select(x => new ComboSelectListItem() { Text = x.Text, Value = x.Value, ICon = x.ICon }).ToList() : new List <ComboSelectListItem>(); SelectedRolesIDs.AddRange(DC.Set <FunctionPrivilege>().Where(x => x.MenuItemId == Entity.ID && x.RoleId != null && x.Allowed == true).Select(x => x.RoleId.Value).ToList()); var data = DC.Set <FrameworkMenu>().ToList(); var topMenu = data.Where(x => x.ParentId == null).ToList().FlatTree(x => x.DisplayOrder); var pids = Entity.GetAllChildrenIDs(DC); AllParents = topMenu.Where(x => x.ID != Entity.ID && !pids.Contains(x.ID) && x.FolderOnly == true).ToList().ToListItems(y => y.PageName, x => x.ID); var modules = GlobalServices.GetRequiredService <GlobalData>().AllModule; var m = modules.Where(x => x.NameSpace != "WalkingTec.Mvvm.Admin.Api").ToList(); List <FrameworkModule> toremove = new List <FrameworkModule>(); foreach (var item in m) { var f = modules.Where(x => x.ClassName == item.ClassName && x.Area?.AreaName == item.Area?.AreaName).FirstOrDefault(); if (f?.IgnorePrivillege == true) { toremove.Add(item); } } toremove.ForEach(x => m.Remove(x)); AllModules = m.ToListItems(y => y.ModuleName, y => y.FullName); if (string.IsNullOrEmpty(Entity.Url) == false && Entity.IsInside == true) { SelectedModule = modules.Where(x => x.IsApi == false && (x.ClassName == Entity.ClassName || x.FullName == Entity.ClassName)).SelectMany(x => x.Actions).FirstOrDefault().Module.FullName; var mm = modules.Where(x => x.FullName == SelectedModule).SelectMany(x => x.Actions).Where(x => x.MethodName != "Index" && x.IgnorePrivillege == false).ToList(); AllActions = mm.ToListItems(y => y.ActionName, y => y.Url); SelectedActionIDs = DC.Set <FrameworkMenu>().Where(x => AllActions.Select(y => y.Value).Contains(x.Url) && x.IsInside == true && x.FolderOnly == false).Select(x => x.Url).ToList(); } }
public override Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { var baseVM = Vm?.Model as BaseVM; var tempSearchTitleId = Guid.NewGuid().ToNoSplitString(); var layuiShow = GlobalServices.GetRequiredService <Configs>().UiOptions.SearchPanel.DefaultExpand ? " layui-show" : string.Empty; output.PreContent.AppendHtml($@" <div class=""layui-collapse"" style=""margin-bottom:5px;"" lay-filter=""{tempSearchTitleId}""> <div class=""layui-colla-item""> <h2 class=""layui-colla-title"">搜索条件 <div style=""text-align:right;margin-top:-43px;"" id=""{tempSearchTitleId}""> <a href=""javascript:void(0)"" class=""layui-btn layui-btn-sm"" id=""{SearchBtnId}""><i class=""layui-icon""></i>搜索</a> {(!ResetBtn ? string.Empty : $@"<button type=""reset"" class=""layui-btn layui-btn-sm"" id=""{ResetBtnId}"">重置</button>")}
public override void Validate() { if (Entity.IsInside == true && Entity.FolderOnly == false) { var modules = GlobalServices.GetRequiredService <GlobalData>().AllModule; var test = DC.Set <FrameworkMenu>().Where(x => x.ClassName == this.SelectedModule && (x.MethodName == null || x.MethodName == "Index") && x.ID != Entity.ID).FirstOrDefault(); if (test != null) { MSD.AddModelError(" error", Program._localizer["ModuleHasSet"]); } } base.Validate(); }
public override void Validate() { if (Entity.IsInside == true && Entity.FolderOnly == false) { var modules = GlobalServices.GetRequiredService <GlobalData>().AllModule; var test = DC.Set <FrameworkMenu>().Where(x => x.ClassName == this.SelectedModule && string.IsNullOrEmpty(x.MethodName) && x.ID != Entity.ID).FirstOrDefault(); if (test != null) { MSD.AddModelError(" error", "该模块已经配置过了"); } } base.Validate(); }
public IActionResult Error() { var ex = HttpContext.Features.Get <IExceptionHandlerPathFeature>(); ActionLog log = new ActionLog(); log.LogType = ActionLogTypesEnum.Exception; log.ActionTime = DateTime.Now; log.ITCode = LoginUserInfo?.ITCode ?? string.Empty; var controllerDes = ex.Error.TargetSite.DeclaringType.GetCustomAttributes(typeof(ActionDescriptionAttribute), false).Cast <ActionDescriptionAttribute>().FirstOrDefault(); var actionDes = ex.Error.TargetSite.GetCustomAttributes(typeof(ActionDescriptionAttribute), false).Cast <ActionDescriptionAttribute>().FirstOrDefault(); var postDes = ex.Error.TargetSite.GetCustomAttributes(typeof(HttpPostAttribute), false).Cast <HttpPostAttribute>().FirstOrDefault(); //给日志的多语言属性赋值 log.ModuleName = controllerDes?.GetDescription(ex.Error.TargetSite.DeclaringType) ?? ex.Error.TargetSite.DeclaringType.Name.Replace("Controller", string.Empty); log.ActionName = actionDes?.GetDescription(ex.Error.TargetSite.DeclaringType) ?? ex.Error.TargetSite.Name; if (postDes != null) { log.ActionName += "[P]"; } log.ActionUrl = ex.Path; log.IP = HttpContext.Connection.RemoteIpAddress.ToString(); log.Remark = ex.Error.ToString(); if (string.IsNullOrEmpty(log.Remark) == false && log.Remark.Length > 1000) { log.Remark = log.Remark.Substring(0, 1000); } DateTime?starttime = HttpContext.Items["actionstarttime"] as DateTime?; if (starttime != null) { log.Duration = DateTime.Now.Subtract(starttime.Value).TotalSeconds; } GlobalServices.GetRequiredService <ILogger <ActionLog> >().Log <ActionLog>(LogLevel.Error, new EventId(), log, null, (a, b) => { return(a.GetLogString()); }); var rv = string.Empty; if (ConfigInfo.IsQuickDebug == true) { rv = ex.Error.ToString().Replace(Environment.NewLine, "</br>"); } else { rv = ex.Error.Message.Replace(Environment.NewLine, "</br>");; } return(BadRequest(rv)); }
public override void Validate() { var modules = GlobalServices.GetRequiredService <GlobalData>().AllModule; var mainAction = modules.Where(x => x.FullName == this.SelectedModule).SelectMany(x => x.Actions).Where(x => x.MethodName == "Index").SingleOrDefault(); if (mainAction != null) { var test = DC.Set <FrameworkMenu>().Where(x => x.Url == mainAction.Url && x.ID != Entity.ID).FirstOrDefault(); if (test != null) { MSD.AddModelError(" error", "该模块已经配置过了"); } } base.Validate(); }
protected override void InitVM() { SelectedRolesIDs.AddRange(DC.Set <FunctionPrivilege>().Where(x => x.MenuItemId == Entity.ID && x.RoleId != null && x.Allowed == true).Select(x => x.RoleId.Value).ToList()); var data = DC.Set <FrameworkMenu>().ToList(); var topMenu = data.Where(x => x.ParentId == null).ToList().FlatTree(x => x.DisplayOrder); var pids = Entity.GetAllChildrenIDs(DC); var modules = GlobalServices.GetRequiredService <GlobalData>().AllModule; if (Entity.Url != null && Entity.IsInside == true) { SelectedModule = modules.Where(x => x.IsApi == true && x.FullName == Entity.ClassName).FirstOrDefault().FullName; var urls = modules.Where(x => x.FullName == SelectedModule && x.IsApi == true).SelectMany(x => x.Actions).Where(x => x.IgnorePrivillege == false).Select(x => x.Url).ToList(); SelectedActionIDs = DC.Set <FrameworkMenu>().Where(x => urls.Contains(x.Url) && x.IsInside == true && x.FolderOnly == false).Select(x => x.MethodName).ToList(); } }
static void Run() { var redisCache = GlobalServices.GetRequiredService <IRedisCache>(); redisCache.KeyDelete("Q_Flag_SignIn1"); redisCache.KeyDelete("Q_Flag_SignIn2"); var stopwatch = new Stopwatch(); stopwatch.Start(); int count = 0; for (int j = 0; j < 50; j++) { Task.Run(async() => { for (int i = 0; i < 5000; i++) { //await redisCache.HSetAsync("Q_Flag_SignIn2", Guid.NewGuid().ToString(), new //{ // userCode = "1850410605", // Longitude = 117.111464, // Latitude = 39.070614, // Place = "压测", // SignInTime = "2018-11-07 16:12:13" //}); await redisCache.LPushAsync("Q_Flag_SignIn1", new { userCode = "1850410605", Longitude = 117.111464, Latitude = 39.070614, Place = "压测", SignInTime = "2018-11-07 16:12:13" }); } count++; if (count == 50) { stopwatch.Stop(); Console.WriteLine($"耗时:{stopwatch.ElapsedMilliseconds}"); } }); } }
protected override void InitVM() { SelectedRolesIDs.AddRange(DC.Set <FunctionPrivilege>().Where(x => x.MenuItemId == Entity.ID && x.RoleId != null && x.Allowed == true).Select(x => x.RoleId.Value).ToList()); var data = DC.Set <FrameworkMenu>().ToList(); var topMenu = data.Where(x => x.ParentId == null).ToList().FlatTree(x => x.DisplayOrder); var pids = Entity.GetAllChildrenIDs(DC); AllParents = topMenu.Where(x => x.ID != Entity.ID && !pids.Contains(x.ID) && x.FolderOnly == true).ToList().ToListItems(y => y.PageName, x => x.ID); var modules = GlobalServices.GetRequiredService <GlobalData>().AllModule; if (ControllerName.Contains("WalkingTec.Mvvm.Mvc.Admin.Controllers")) { var m = modules.Where(x => x.NameSpace != "WalkingTec.Mvvm.Admin.Api").ToList(); List <FrameworkModule> toremove = new List <FrameworkModule>(); foreach (var item in m) { var f = modules.Where(x => x.ClassName == item.ClassName && x.Area?.AreaName == item.Area?.AreaName).FirstOrDefault(); if (f?.IgnorePrivillege == true) { toremove.Add(item); } } toremove.ForEach(x => m.Remove(x)); AllModules = m.ToListItems(y => y.ModuleName, y => y.FullName); } if (Entity.Url != null) { if (ControllerName.Contains("WalkingTec.Mvvm.Mvc.Admin.Controllers")) { SelectedModule = modules.Where(x => x.IsApi == false).SelectMany(x => x.Actions).Where(x => x.Url == Entity.Url).FirstOrDefault().Module.FullName; } else { SelectedModule = modules.Where(x => x.IsApi == true).SelectMany(x => x.Actions).Where(x => x.Url == Entity.Url).FirstOrDefault().Module.FullName; } var m = modules.Where(x => x.FullName == SelectedModule).SelectMany(x => x.Actions).Where(x => x.MethodName != "Index" && x.IgnorePrivillege == false).ToList(); AllActions = m.ToListItems(y => y.ActionName, y => y.Url); SelectedActionIDs = DC.Set <FrameworkMenu>().Where(x => AllActions.Select(y => y.Value).Contains(x.Url) && x.IsInside == true && x.FolderOnly == false).Select(x => x.Url).ToList(); } }
public JsonResult GetActionsByModelId(Guid Id) { var modules = GlobalServices.GetRequiredService <GlobalData>().AllModule; var m = DC.Set <FrameworkAction>().Include(x => x.Module.Area).Where(x => x.ModuleId == Id && x.MethodName != "Index").ToList(); List <FrameworkAction> toremove = new List <FrameworkAction>(); foreach (var item in m) { var f = modules.Where(x => x.ClassName == item.Module.ClassName && x.Area?.AreaName == item.Module.Area?.AreaName).FirstOrDefault(); var a = f?.Actions.Where(x => x.MethodName == item.MethodName).FirstOrDefault(); if (a?.IgnorePrivillege == true) { toremove.Add(item); } } toremove.ForEach(x => m.Remove(x)); var actions = m.ToListItems(y => y.ActionName, y => y.ID); actions.ForEach(x => x.Selected = true); return(Json(actions)); }
public override void OnActionExecuting(ActionExecutingContext context) { var controller = context.Controller as IBaseController; if (controller == null) { base.OnActionExecuting(context); return; } if (controller.ConfigInfo.IsQuickDebug && controller is BaseApiController) { base.OnActionExecuting(context); return; } ControllerActionDescriptor ad = context.ActionDescriptor as ControllerActionDescriptor; var lg = GlobalServices.GetRequiredService <LinkGenerator>(); var u = lg.GetPathByAction(ad.ActionName, ad.ControllerName, new { area = context.RouteData.Values["area"] }); if (u == null) { u = lg.GetPathByAction(ad.ActionName, ad.ControllerName, new { area = context.RouteData.Values["area"], id = 0 }); } if (u.EndsWith("/0")) { u = u.Substring(0, u.Length - 2); if (controller is BaseApiController) { u = u + "/{id}"; } } controller.BaseUrl = u + context.HttpContext.Request.QueryString.ToUriComponent();; //如果是QuickDebug模式,或者Action或Controller上有AllRightsAttribute标记都不需要判断权限 //如果用户登录信息为空,也不需要判断权限,BaseController中会对没有登录的用户做其他处理 var isPublic = ad.MethodInfo.IsDefined(typeof(PublicAttribute), false) || ad.ControllerTypeInfo.IsDefined(typeof(PublicAttribute), false); if (!isPublic) { isPublic = ad.MethodInfo.IsDefined(typeof(AllowAnonymousAttribute), false) || ad.ControllerTypeInfo.IsDefined(typeof(AllowAnonymousAttribute), false); } var isAllRights = ad.MethodInfo.IsDefined(typeof(AllRightsAttribute), false) || ad.ControllerTypeInfo.IsDefined(typeof(AllRightsAttribute), false); var isDebug = ad.MethodInfo.IsDefined(typeof(DebugOnlyAttribute), false) || ad.ControllerTypeInfo.IsDefined(typeof(DebugOnlyAttribute), false); if (controller.ConfigInfo.IsFilePublic == true) { if (ad.ControllerName == "_Framework" && (ad.MethodInfo.Name == "GetFile" || ad.MethodInfo.Name == "ViewFile")) { isPublic = true; } if (ad.ControllerTypeInfo.FullName == "WalkingTec.Mvvm.Admin.Api.FileApiController" && (ad.MethodInfo.Name == "GetFileName" || ad.MethodInfo.Name == "GetFile" || ad.MethodInfo.Name == "DownloadFile")) { isPublic = true; } } if (isDebug) { if (controller.ConfigInfo.IsQuickDebug) { base.OnActionExecuting(context); } else { if (controller is BaseController c) { context.Result = c.Content(Program._localizer["DebugOnly"]); } else if (controller is ControllerBase c2) { context.Result = c2.BadRequest(Program._localizer["DebugOnly"]); } } return; } if (isPublic == true) { base.OnActionExecuting(context); return; } if (controller.LoginUserInfo == null) { if (controller is ControllerBase ctrl) { //if it's a layui search request,returns a layui format message so that it can parse if (ctrl.Request.Headers.ContainsKey("layuisearch")) { ContentResult cr = new ContentResult() { Content = "{\"Data\":[],\"Count\":0,\"Page\":1,\"PageCount\":0,\"Msg\":\"" + Program._localizer["NeedLogin"] + "\",\"Code\":401}", ContentType = "application/json", StatusCode = 200 }; context.Result = cr; } else { if (ctrl.HttpContext.Request.Headers.ContainsKey("Authorization")) { context.Result = ctrl.Unauthorized(JwtBearerDefaults.AuthenticationScheme); } else { if (controller is BaseApiController) { ContentResult cr = new ContentResult() { Content = Program._localizer["NeedLogin"], ContentType = "text/html", StatusCode = 401 }; context.Result = cr; } else { string lp = GlobalServices.GetRequiredService <IOptions <CookieOptions> >().Value.LoginPath; if (lp.StartsWith("/")) { lp = "~" + lp; } if (lp.StartsWith("~/")) { lp = ctrl.Url.Content(lp); } ContentResult cr = new ContentResult() { Content = $"<script>window.location.href='{lp}';</script>", ContentType = "text/html", StatusCode = 200 }; //context.HttpContext.Response.Headers.Add("IsScript", "true"); context.Result = cr; //context.Result = ctrl.Redirect(GlobalServices.GetRequiredService<IOptions<CookieOptions>>().Value.LoginPath); } } } } //context.HttpContext.ChallengeAsync().Wait(); } else { if (isAllRights == false) { bool canAccess = controller.LoginUserInfo.IsAccessable(controller.BaseUrl); if (canAccess == false && controller.ConfigInfo.IsQuickDebug == false) { if (controller is ControllerBase ctrl) { //if it's a layui search request,returns a layui format message so that it can parse if (ctrl.Request.Headers.ContainsKey("layuisearch")) { ContentResult cr = new ContentResult() { Content = "{\"Data\":[],\"Count\":0,\"Page\":1,\"PageCount\":0,\"Msg\":\"" + Program._localizer["NoPrivilege"] + "\",\"Code\":403}", ContentType = "application/json", StatusCode = 200 }; context.Result = cr; } else { if (ctrl.HttpContext.Request.Headers.ContainsKey("Authorization")) { context.Result = ctrl.Forbid(JwtBearerDefaults.AuthenticationScheme); } else { ContentResult cr = new ContentResult() { Content = Program._localizer["NoPrivilege"], ContentType = "text/html", StatusCode = 403 }; context.Result = cr; } } } } } } base.OnActionExecuting(context); }
public override void OnActionExecuting(ActionExecutingContext context) { var controller = context.Controller as IBaseController; if (controller == null) { base.OnActionExecuting(context); return; } if (controller.ConfigInfo.IsQuickDebug && controller is BaseApiController) { base.OnActionExecuting(context); return; } ControllerActionDescriptor ad = context.ActionDescriptor as ControllerActionDescriptor; if (controller is BaseController) { controller.BaseUrl = $"/{ad.ControllerName}/{ad.ActionName}"; controller.BaseUrl += context.HttpContext.Request.QueryString.ToUriComponent(); if (context.RouteData.Values["area"] != null) { controller.BaseUrl = $"/{context.RouteData.Values["area"]}{controller.BaseUrl}"; } } if (controller is BaseApiController) { var lg = GlobalServices.GetRequiredService <LinkGenerator>(); var u = lg.GetPathByAction(ad.ActionName, ad.ControllerName, new { area = context.RouteData.Values["area"] }); if (u == null) { u = lg.GetPathByAction(ad.ActionName, ad.ControllerName, new { area = context.RouteData.Values["area"], id = 0 }); } if (u.EndsWith("/0")) { u = u.Substring(0, u.Length - 2); u = u + "/{id}"; } controller.BaseUrl = u; } //如果是QuickDebug模式,或者Action或Controller上有AllRightsAttribute标记都不需要判断权限 //如果用户登录信息为空,也不需要判断权限,BaseController中会对没有登录的用户做其他处理 var isPublic = ad.MethodInfo.IsDefined(typeof(PublicAttribute), false) || ad.ControllerTypeInfo.IsDefined(typeof(PublicAttribute), false); var isAllRights = ad.MethodInfo.IsDefined(typeof(AllRightsAttribute), false) || ad.ControllerTypeInfo.IsDefined(typeof(AllRightsAttribute), false); var isDebug = ad.MethodInfo.IsDefined(typeof(DebugOnlyAttribute), false) || ad.ControllerTypeInfo.IsDefined(typeof(DebugOnlyAttribute), false); if (controller.ConfigInfo.IsFilePublic == true) { if (ad.ControllerName == "_Framework" && (ad.MethodInfo.Name == "GetFile" || ad.MethodInfo.Name == "ViewFile")) { isPublic = true; } } if (isDebug) { if (controller.ConfigInfo.IsQuickDebug) { base.OnActionExecuting(context); } else { if (controller is BaseController c) { context.Result = c.Content("该地址只能在调试模式下访问"); } else if (controller is ControllerBase c2) { context.Result = c2.BadRequest("该地址只能在调试模式下访问"); } } return; } if (isPublic == true) { base.OnActionExecuting(context); return; } if (controller.LoginUserInfo == null) { var publicMenu = controller.GlobaInfo.AllMenus .Where(x => x.Url != null && x.Url.ToLower() == "/" + ad.ControllerName.ToLower() + "/" + ad.ActionName && x.IsPublic == true) .FirstOrDefault(); if (publicMenu == null) { if (controller is BaseController c) { context.Result = new ContentResult { Content = $"<script>window.location.href = '/Login/Login?rd={HttpUtility.UrlEncode(controller.BaseUrl)}'</script>", ContentType = "text/html" }; } else if (controller is ControllerBase c2) { context.Result = c2.Unauthorized(); } return; } } else { if (isAllRights == false) { bool canAccess = controller.LoginUserInfo.IsAccessable(controller.BaseUrl); if (canAccess == false && controller.ConfigInfo.IsQuickDebug == false) { if (controller is BaseController c) { throw new Exception("您没有访问该页面的权限"); } else if (controller is ControllerBase c2) { context.Result = c2.Unauthorized(); } } } } base.OnActionExecuting(context); }
public override void Process(TagHelperContext context, TagHelperOutput output) { string Value = null; output.TagName = "input"; output.TagMode = TagMode.StartTagOnly; output.Attributes.Add("type", "text"); output.Attributes.Add("name", Field.Name); if (Range.HasValue && Range.Value && string.IsNullOrEmpty(RangeSplit)) { RangeSplit = "~"; } if (DefaultValue != null) { Value = DefaultValue; } else { if (Field.ModelExplorer.ModelType == typeof(string)) { Value = Field.Model?.ToString() ?? Value; } else if (Range.HasValue && Range.Value && Field.ModelExplorer.ModelType == typeof(DateRange)) { var dateRange = Field.Model as DateRange; if (string.IsNullOrEmpty(Format)) { Value = dateRange?.ToString(DateTimeFormatDic[Type], RangeSplit) ?? Value; } else { Value = dateRange?.ToString(Format, RangeSplit) ?? Value; } } else if (Field.ModelExplorer.ModelType == typeof(TimeSpan) || Field.ModelExplorer.ModelType == typeof(TimeSpan?)) { TimeSpan?df = Field.Model as TimeSpan?; if (df == TimeSpan.MinValue) { df = null; } Value = df?.ToString(); } else { DateTime?df = Field.Model as DateTime?; if (df == DateTime.MinValue) { df = null; } if (string.IsNullOrEmpty(Format)) { Value = df?.ToString(DateTimeFormatDic[Type]) ?? Value; } else { Value = df?.ToString(Format) ?? Value; } } } output.Attributes.Add("value", Value); output.Attributes.Add("class", "layui-input"); if (GlobalServices.GetRequiredService <Configs>().UiOptions.DateTime.DefaultReadonly) { output.Attributes.Add("readonly", "readonly"); } if (!string.IsNullOrEmpty(Min)) { if (int.TryParse(Min, out int minRes)) { Min = minRes.ToString(); } else { Min = $"'{Min}'"; } } if (!string.IsNullOrEmpty(Max)) { if (int.TryParse(Max, out int maxRes)) { Max = maxRes.ToString(); } else { Max = $"'{Max}'"; } } if (Lang == null) { if (Enum.TryParse <DateTimeLangEnum>(Program._localizer["LayuiDateLan"], true, out var testlang)) { Lang = testlang; } } var content = $@" <script> layui.use(['laydate'],function(){{ var laydate = layui.laydate; var dateIns = laydate.render({{ elem: '#{Id}', type: '{Type.ToString().ToLower()}' {(string.IsNullOrEmpty(RangeSplit) ? string.Empty : $",range:'{RangeSplit}'")} {(string.IsNullOrEmpty(Format) ? string.Empty : $",format: '{Format}'")} {(string.IsNullOrEmpty(Min) ? string.Empty : $",min: {Min}")} {(string.IsNullOrEmpty(Max) ? string.Empty : $",max: {Max}")} {(!ZIndex.HasValue ? string.Empty : $",zIndex: {ZIndex.Value}")} {(!ShowBottom.HasValue ? string.Empty : $",showBottom: {ShowBottom.Value.ToString().ToLower()}")} {(!ConfirmOnly.HasValue ? string.Empty : ShowBottom.HasValue && ShowBottom.Value && ConfirmOnly.Value || !ShowBottom.HasValue && ConfirmOnly.Value ? $",btns: ['confirm']" : string.Empty)} {(!Calendar.HasValue ? string.Empty : $",calendar: {Calendar.Value.ToString().ToLower()}")} {(!Lang.HasValue ? string.Empty : $",lang: '{Lang.Value.ToString().ToLower()}'")} {(Mark == null || Mark.Count == 0 ? string.Empty : $",mark: {JsonConvert.SerializeObject(Mark)}")} {(string.IsNullOrEmpty(ReadyFunc) ? string.Empty : $",ready: function(value){{{ReadyFunc}(value,dateIns)}}")} {(string.IsNullOrEmpty(ChangeFunc) ? string.Empty : $",change: function(value,date,endDate){{{ChangeFunc}(value,date,endDate,dateIns)}}")} {(string.IsNullOrEmpty(DoneFunc) ? string.Empty : $",done: function(value,date,endDate){{{DoneFunc}(value,date,endDate,dateIns)}}")} }}); }}) </script> "; output.PostElement.AppendHtml(content); base.Process(context, output); }
public override void Process(TagHelperContext context, TagHelperOutput output) { if (Loading == null) { Loading = true; } var vmQualifiedName = Vm.Model.GetType().AssemblyQualifiedName; vmQualifiedName = vmQualifiedName.Substring(0, vmQualifiedName.LastIndexOf(", Version=", StringComparison.CurrentCulture)); var tempGridTitleId = Guid.NewGuid().ToNoSplitString(); output.TagName = "table"; output.Attributes.Add("id", Id); output.Attributes.Add("lay-filter", Id); output.TagMode = TagMode.StartTagAndEndTag; if (Limit == null) { Limit = GlobalServices.GetRequiredService <Configs>()?.UiOptions.DataTable.RPP; } if (Limits == null) { Limits = new int[] { 10, 20, 50, 80, 100, 150, 200 }; if (!Limits.Contains(Limit.Value)) { var list = Limits.ToList(); list.Add(Limit.Value); Limits = list.OrderBy(x => x).ToArray(); } } if (UseLocalData) // 不需要分页 { ListVM.NeedPage = false; } else { if (string.IsNullOrEmpty(Url)) { Url = "/_Framework/GetPagingData"; } if (Filter == null) { Filter = new Dictionary <string, object>(); } Filter.Add("_DONOT_USE_VMNAME", vmQualifiedName); Filter.Add("_DONOT_USE_CS", ListVM.CurrentCS); Filter.Add("SearcherMode", ListVM.SearcherMode); if (ListVM.Ids != null && ListVM.Ids.Count > 0) { Filter.Add("Ids", ListVM.Ids); } // 为首次加载添加Searcher查询参数 if (ListVM.Searcher != null) { var props = ListVM.Searcher.GetType().GetProperties(); props = props.Where(x => !_excludeTypes.Contains(x.PropertyType)).ToArray(); foreach (var prop in props) { if (!_excludeParams.Contains(prop.Name)) { if (prop.PropertyType.IsGenericType == false || (prop.PropertyType.GenericTypeArguments[0] != typeof(ComboSelectListItem) && prop.PropertyType.GenericTypeArguments[0] != typeof(TreeSelectListItem))) { Filter.Add($"Searcher.{prop.Name}", prop.GetValue(ListVM.Searcher)); } } } } } // 是否需要分页 var page = ListVM.NeedPage; #region 生成 Layui 所需的表头 var rawCols = ListVM?.GetHeaders(); var maxDepth = (ListVM?.ChildrenDepth) ?? 1; var layuiCols = new List <List <LayuiColumn> >(); var tempCols = new List <LayuiColumn>(); layuiCols.Add(tempCols); // 添加复选框 if (!HiddenCheckbox) { var checkboxHeader = new LayuiColumn() { Type = LayuiColumnTypeEnum.Checkbox, LAY_CHECKED = CheckedAll, Rowspan = maxDepth, Fixed = GridColumnFixedEnum.Left, UnResize = true, //Width = 45 }; tempCols.Add(checkboxHeader); } // 添加序号列 if (!HiddenGridIndex) { var gridIndex = new LayuiColumn() { Type = LayuiColumnTypeEnum.Numbers, Rowspan = maxDepth, Fixed = GridColumnFixedEnum.Left, UnResize = true, //Width = 45 }; tempCols.Add(gridIndex); } var nextCols = new List <IGridColumn <TopBasePoco> >();// 下一级列头 generateColHeader(rawCols, nextCols, tempCols, maxDepth); if (nextCols.Count > 0) { CalcChildCol(layuiCols, nextCols, maxDepth, 1); } if (layuiCols.Count > 0 && layuiCols[0].Count > 0) { layuiCols[0][0].TotalRowText = ListVM?.TotalText; } #endregion #region 处理 DataTable 操作按钮 var actionCol = ListVM?.GridActions; var rowBtnStrBuilder = new StringBuilder(); // Grid 行内按钮 var toolBarBtnStrBuilder = new StringBuilder(); // Grid 工具条按钮 var gridBtnEventStrBuilder = new StringBuilder(); // Grid 按钮事件 if (actionCol != null && actionCol.Count > 0) { var vm = Vm.Model as BaseVM; foreach (var item in actionCol) { AddSubButton(vmQualifiedName, rowBtnStrBuilder, toolBarBtnStrBuilder, gridBtnEventStrBuilder, vm, item); } } #endregion #region DataTable var vmName = string.Empty; if (VMType != null) { var vmQualifiedName1 = VMType.AssemblyQualifiedName; vmName = vmQualifiedName1.Substring(0, vmQualifiedName1.LastIndexOf(", Version=", StringComparison.CurrentCulture)); } output.PostElement.AppendHtml($@" <script> var {Id}option = null; /* 监听工具条 */ function wtToolBarFunc_{Id}(obj){{ //注:tool是工具条事件名,test是table原始容器的属性 lay-filter=""对应的值"" var data = obj.data, layEvent = obj.event, tr = obj.tr; //获得当前行 tr 的DOM对象 {(gridBtnEventStrBuilder.Length == 0 ? string.Empty : $@"switch(layEvent){{{gridBtnEventStrBuilder}default:break;}}")} return; }} layui.use(['table'], function(){{ var table = layui.table; {Id}option = {{ elem: '#{Id}' ,id: '{Id}' {(!NeedShowTotal ? string.Empty : ",totalRow:true")} {(UseLocalData ? string.Empty : $",url: '{Url}'")} {(Filter == null || Filter.Count == 0 ? string.Empty : $",where: {JsonConvert.SerializeObject(Filter)}")} {(Method == null ? ",method:'post'" : $",method: '{Method.Value.ToString().ToLower()}'")} {(Loading ?? true ? string.Empty : ",loading:false")} {(page ? string.Empty : ",page:{layout:['count']}")} {(page ? $",limit:{Limit}" : $",limit:{(UseLocalData ? ListVM.GetEntityList().Count().ToString() : "0")}")} {(page ? (Limits == null || Limits.Length == 0 ? string.Empty : $",limits:[{string.Join(',', Limits)}]" ) : string.Empty)} {(!Width.HasValue ? string.Empty : $",width: {Width.Value}")} {(!Height.HasValue ? string.Empty : (Height.Value >= 0 ? $",height: {Height.Value}" : $",height: 'full{Height.Value}'"))} ,cols:{JsonConvert.SerializeObject(layuiCols, _jsonSerializerSettings)} {(!Skin.HasValue ? string.Empty : $",skin: '{Skin.Value.ToString().ToLower()}'")} {(Even.HasValue && !Even.Value ? $",even: false" : string.Empty)} {(!Size.HasValue ? string.Empty : $",size: '{Size.Value.ToString().ToLower()}'")} ,done: function(res,curr,count){{ var tab = $('#{Id} + .layui-table-view');tab.find('table').css('border-collapse','separate'); {(Height == null ? $"tab.css('overflow','hidden').addClass('donotuse_fill donotuse_pdiv');tab.children('.layui-table-box').addClass('donotuse_fill donotuse_pdiv').css('height','100px');tab.find('.layui-table-main').addClass('donotuse_fill');tab.find('.layui-table-header').css('min-height','40px');ff.triggerResize();" : string.Empty)} {(MultiLine == true ? $"tab.find('.layui-table-cell').css('height','auto').css('white-space','normal');" : string.Empty)} {(string.IsNullOrEmpty(DoneFunc) ? string.Empty : $"{DoneFunc}(res,curr,count)")}
public override void OnResultExecuted(ResultExecutedContext context) { var ctrl = context.Controller as IBaseController; if (ctrl == null) { base.OnResultExecuted(context); return; } var ctrlActDesc = context.ActionDescriptor as ControllerActionDescriptor; var nolog = ctrlActDesc.MethodInfo.IsDefined(typeof(NoLogAttribute), false) || ctrlActDesc.ControllerTypeInfo.IsDefined(typeof(NoLogAttribute), false); //如果是来自Error,则已经记录过日志,跳过 if (ctrlActDesc.ControllerName == "_Framework" && ctrlActDesc.ActionName == "Error") { return; } if (nolog == false) { var log = new ActionLog(); var ctrlDes = ctrlActDesc.ControllerTypeInfo.GetCustomAttributes(typeof(ActionDescriptionAttribute), false).Cast <ActionDescriptionAttribute>().FirstOrDefault(); var actDes = ctrlActDesc.MethodInfo.GetCustomAttributes(typeof(ActionDescriptionAttribute), false).Cast <ActionDescriptionAttribute>().FirstOrDefault(); var postDes = ctrlActDesc.MethodInfo.GetCustomAttributes(typeof(HttpPostAttribute), false).Cast <HttpPostAttribute>().FirstOrDefault(); log.LogType = context.Exception == null ? ActionLogTypesEnum.Normal : ActionLogTypesEnum.Exception; log.ActionTime = DateTime.Now; log.ITCode = ctrl.LoginUserInfo?.ITCode ?? string.Empty; // 给日志的多语言属性赋值 log.ModuleName = ctrlDes?.GetDescription(ctrl) ?? ctrlActDesc.ControllerName; log.ActionName = actDes?.GetDescription(ctrl) ?? ctrlActDesc.ActionName + (postDes == null ? string.Empty : "[P]"); log.ActionUrl = context.HttpContext.Request.Path; log.IP = context.HttpContext.GetRemoteIpAddress(); log.Remark = context.Exception?.ToString() ?? string.Empty; if (string.IsNullOrEmpty(log.Remark) == false && log.Remark.Length > 2000) { log.Remark = log.Remark.Substring(0, 2000); } var starttime = context.HttpContext.Items["actionstarttime"] as DateTime?; if (starttime != null) { log.Duration = DateTime.Now.Subtract(starttime.Value).TotalSeconds; } try { GlobalServices.GetRequiredService <ILogger <ActionLog> >().Log <ActionLog>(LogLevel.Information, new EventId(), log, null, (a, b) => { return(a.GetLogString()); }); } catch { } } if (context.Exception != null) { context.ExceptionHandled = true; if (ctrl.ConfigInfo.IsQuickDebug == true) { context.HttpContext.Response.WriteAsync(context.Exception.ToString()); } else { context.HttpContext.Response.WriteAsync(Program._localizer["PageError"]); } } base.OnResultExecuted(context); }
public override void OnActionExecuting(ActionExecutingContext context) { var ctrl = context.Controller as IBaseController; if (ctrl == null) { base.OnActionExecuting(context); return; } if (context.HttpContext.Items.ContainsKey("actionstarttime") == false) { context.HttpContext.Items.Add("actionstarttime", DateTime.Now); } var ctrlActDesc = context.ActionDescriptor as ControllerActionDescriptor; var log = new SimpleLog();// 初始化log备用 var ctrlDes = ctrlActDesc.ControllerTypeInfo.GetCustomAttributes(typeof(ActionDescriptionAttribute), false).Cast <ActionDescriptionAttribute>().FirstOrDefault(); var actDes = ctrlActDesc.MethodInfo.GetCustomAttributes(typeof(ActionDescriptionAttribute), false).Cast <ActionDescriptionAttribute>().FirstOrDefault(); var postDes = ctrlActDesc.MethodInfo.GetCustomAttributes(typeof(HttpPostAttribute), false).Cast <HttpPostAttribute>().FirstOrDefault(); var validpostonly = ctrlActDesc.MethodInfo.GetCustomAttributes(typeof(ValidateFormItemOnlyAttribute), false).Cast <ValidateFormItemOnlyAttribute>().FirstOrDefault(); log.ITCode = ctrl.LoginUserInfo?.ITCode ?? string.Empty; //给日志的多语言属性赋值 log.ModuleName = ctrlDes?.GetDescription(ctrl) ?? ctrlActDesc.ControllerName; log.ActionName = actDes?.GetDescription(ctrl) ?? ctrlActDesc.ActionName + (postDes == null ? string.Empty : "[P]"); log.ActionUrl = ctrl.BaseUrl; log.IP = context.HttpContext.Connection.RemoteIpAddress.ToString(); ctrl.Log = log; foreach (var item in context.ActionArguments) { if (item.Value is BaseVM) { var model = item.Value as BaseVM; model.Session = new SessionServiceProvider(context.HttpContext.Session); model.Cache = ctrl.Cache; model.LoginUserInfo = ctrl.LoginUserInfo; model.DC = ctrl.DC; model.MSD = new ModelStateServiceProvider(ctrl.ModelState); model.FC = new Dictionary <string, object>(); model.CreatorAssembly = this.GetType().Assembly.FullName; model.FromFixedCon = ctrlActDesc.MethodInfo.IsDefined(typeof(FixConnectionAttribute), false) || ctrlActDesc.ControllerTypeInfo.IsDefined(typeof(FixConnectionAttribute), false);; model.CurrentCS = ctrl.CurrentCS; model.Log = ctrl.Log; model.CurrentUrl = ctrl.BaseUrl; model.ConfigInfo = (Configs)context.HttpContext.RequestServices.GetService(typeof(Configs)); model.DataContextCI = model.ConfigInfo.ConnectionStrings.Where(x => x.Key.ToLower() == ctrl.CurrentCS.ToLower()).Select(x => x.DcConstructor).FirstOrDefault(); model.Controller = ctrl; model.ControllerName = ctrl.GetType().FullName; model.Localizer = ctrl.Localizer; var programtype = ctrl.GetType().Assembly.GetTypes().Where(x => x.Name == "Program").FirstOrDefault(); if (programtype != null) { model.Localizer = GlobalServices.GetRequiredService(typeof(IStringLocalizer <>).MakeGenericType(programtype)) as IStringLocalizer; } if (ctrl is BaseController c) { model.WindowIds = c.WindowIds; model.UIService = c.UIService; } else { model.WindowIds = ""; model.UIService = new DefaultUIService(); } try { var f = context.HttpContext.Request.Form; foreach (var key in f.Keys) { if (model.FC.Keys.Contains(key) == false) { model.FC.Add(key, f[key]); } } if (context.HttpContext.Request.QueryString != null) { foreach (var key in context.HttpContext.Request.Query.Keys) { if (model.FC.Keys.Contains(key) == false) { model.FC.Add(key, context.HttpContext.Request.Query[key]); } } } } catch { } if (ctrl is BaseApiController apictrl) { //apictrl.TryValidateModel(model); apictrl.HttpContext.Request.Body.Position = 0; StreamReader tr = new StreamReader(apictrl.HttpContext.Request.Body); string body = tr.ReadToEnd(); var obj = JsonConvert.DeserializeObject(body) as JObject; var fields = GetJsonFields(obj); foreach (var field in fields) { model.FC.Add(field, null); } } if (model is IBaseCRUDVM <TopBasePoco> crud) { var pros = crud.Entity.GetType().GetProperties(); foreach (var pro in pros) { //找到类型为List<xxx>的字段 if (pro.PropertyType.GenericTypeArguments.Count() > 0) { //获取xxx的类型 var ftype = pro.PropertyType.GenericTypeArguments.First(); //如果xxx继承自TopBasePoco if (ftype.IsSubclassOf(typeof(TopBasePoco))) { //界面传过来的子表数据 if (pro.GetValue(crud.Entity) is IEnumerable <TopBasePoco> list && list.Count() == 0) { pro.SetValue(crud.Entity, null); } } } } } //如果ViewModel T继承自IBaseBatchVM<BaseVM>,则自动为其中的ListVM和EditModel初始化数据 if (model is IBaseBatchVM <BaseVM> ) { var temp = model as IBaseBatchVM <BaseVM>; if (temp.ListVM != null) { temp.ListVM.CopyContext(model); temp.ListVM.Ids = temp.Ids == null ? new List <string>() : temp.Ids.ToList(); temp.ListVM.SearcherMode = ListVMSearchModeEnum.Batch; temp.ListVM.NeedPage = false; } if (temp.LinkedVM != null) { temp.LinkedVM.CopyContext(model); } if (temp.ListVM != null) { //绑定ListVM的OnAfterInitList事件,当ListVM的InitList完成时,自动将操作列移除 temp.ListVM.OnAfterInitList += (self) => { self.RemoveActionColumn(); self.RemoveAction(); self.AddErrorColumn(); }; if (temp.ListVM.Searcher != null) { var searcher = temp.ListVM.Searcher; searcher.CopyContext(model); } temp.ListVM.DoInitListVM(); } temp.LinkedVM?.DoInit(); } if (model is IBaseImport <BaseTemplateVM> ) { var template = (model as IBaseImport <BaseTemplateVM>).Template; template.CopyContext(model); template.DoReInit(); } model.Validate(); var invalid = ctrl.ModelState.Where(x => x.Value.ValidationState == Microsoft.AspNetCore.Mvc.ModelBinding.ModelValidationState.Invalid).Select(x => x.Key).ToList(); if ((ctrl as ControllerBase).Request.Method.ToLower() == "put" || validpostonly != null) { foreach (var v in invalid) { if (model.FC.ContainsKey(v) == false) { ctrl.ModelState.Remove(v); } } } if (ctrl is BaseController) { var reinit = model.GetType().GetTypeInfo().GetCustomAttributes(typeof(ReInitAttribute), false).Cast <ReInitAttribute>().SingleOrDefault(); if (ctrl.ModelState.IsValid) { if (reinit != null && (reinit.ReInitMode == ReInitModes.SUCCESSONLY || reinit.ReInitMode == ReInitModes.ALWAYS)) { model.DoReInit(); } } else { if (reinit == null || (reinit.ReInitMode == ReInitModes.FAILEDONLY || reinit.ReInitMode == ReInitModes.ALWAYS)) { model.DoReInit(); } } } //如果是子表外键验证错误,例如Entity.Majors[0].SchoolId为空这种错误,则忽略。因为框架会在添加修改的时候自动给外键赋值 var toremove = ctrl.ModelState.Select(x => x.Key).Where(x => Regex.IsMatch(x, ".*?\\[.*?\\]\\..*?id", RegexOptions.IgnoreCase)); foreach (var r in toremove) { ctrl.ModelState.Remove(r); } } } base.OnActionExecuting(context); }
public static async Task <T> CallAPI <T>(this FrameworkDomain self, string url, HttpMethodEnum method, HttpContent content, ErrorObj error = null, string errormsg = null, int?timeout = null, string proxy = null) { var factory = GlobalServices.GetRequiredService <IHttpClientFactory>(); try { if (string.IsNullOrEmpty(url)) { return(default(T)); } //新建http请求 var client = factory.CreateClient(self.Name); //如果配置了代理,则使用代理 //设置超时 if (timeout.HasValue) { client.Timeout = new TimeSpan(0, 0, 0, timeout.Value, 0); } //填充表单数据 HttpResponseMessage res = null; switch (method) { case HttpMethodEnum.GET: res = await client.GetAsync(url); break; case HttpMethodEnum.POST: res = await client.PostAsync(url, content); break; case HttpMethodEnum.PUT: res = await client.PutAsync(url, content); break; case HttpMethodEnum.DELETE: res = await client.DeleteAsync(url); break; default: break; } T rv = default(T); if (res == null) { return(rv); } if (res.IsSuccessStatusCode == true) { rv = JsonConvert.DeserializeObject <T>(await res.Content.ReadAsStringAsync()); } else { if (res.StatusCode == System.Net.HttpStatusCode.BadRequest) { error = JsonConvert.DeserializeObject <ErrorObj>(await res.Content.ReadAsStringAsync()); } else { errormsg = await res.Content.ReadAsStringAsync(); } } return(rv); } catch (Exception ex) { errormsg = ex.ToString(); return(default(T)); } }
public override void Process(TagHelperContext context, TagHelperOutput output) { if (Loading == null) { Loading = true; } var vmQualifiedName = Vm.Model.GetType().AssemblyQualifiedName; vmQualifiedName = vmQualifiedName.Substring(0, vmQualifiedName.LastIndexOf(", Version=")); var tempGridTitleId = Guid.NewGuid().ToNoSplitString(); output.TagName = "table"; output.Attributes.Add("id", Id); output.Attributes.Add("lay-filter", Id); output.TagMode = TagMode.StartTagAndEndTag; //IEnumerable<TopBasePoco> data = null; if (Limit == null) { Limit = GlobalServices.GetRequiredService <Configs>()?.RPP; } if (Limits == null) { Limits = new int[] { 10, 20, 50, 80, 100, 150, 200 }; if (!Limits.Contains(Limit.Value)) { var list = Limits.ToList(); list.Add(Limit.Value); Limits = list.OrderBy(x => x).ToArray(); } } // TODO 转换有问题 Page = ListVM.NeedPage; if (UseLocalData) { // 不需要分页 ListVM.NeedPage = false; //data = ListVM.GetEntityList().ToList(); } else if (string.IsNullOrEmpty(Url)) { Url = "/_Framework/GetPagingData"; if (Filter == null) { Filter = new Dictionary <string, object>(); } Filter.Add("_DONOT_USE_VMNAME", vmQualifiedName); Filter.Add("_DONOT_USE_CS", ListVM.CurrentCS); Filter.Add("SearcherMode", ListVM.SearcherMode); if (ListVM.Ids != null && ListVM.Ids.Count > 0) { Filter.Add("Ids", ListVM.Ids); } // 为首次加载添加Searcher查询参数 if (ListVM.Searcher != null) { var props = ListVM.Searcher.GetType().GetProperties(); props = props.Where(x => !_excludeTypes.Contains(x.PropertyType)).ToArray(); foreach (var prop in props) { if (!_excludeParams.Contains(prop.Name)) { Filter.Add($"Searcher.{prop.Name}", prop.GetValue(ListVM.Searcher)); } } } } var request = new Dictionary <string, object> { { "pageName", "Searcher.Page" }, //页码的参数名称,默认:page { "limitName", "Searcher.Limit" }, //每页数据量的参数名,默认:limit }; var response = new Dictionary <string, object> { { "statusName", "Code" }, //数据状态的字段名称,默认:code { "statusCode", 200 }, //成功的状态码,默认:0 { "msgName", "Msg" }, //状态信息的字段名称,默认:msg { "countName", "Count" }, //数据总数的字段名称,默认:count { "dataName", "Data" } //数据列表的字段名称,默认:data }; #region 生成 Layui 所需的表头 var rawCols = ListVM?.GetHeaders(); var maxDepth = (ListVM?.ChildrenDepth) ?? 1; var layuiCols = new List <List <LayuiColumn> >(); var tempCols = new List <LayuiColumn>(); layuiCols.Add(tempCols); // 添加复选框 if (!HiddenCheckbox) { var checkboxHeader = new LayuiColumn() { Type = LayuiColumnTypeEnum.Checkbox, LAY_CHECKED = CheckedAll, Rowspan = maxDepth }; tempCols.Add(checkboxHeader); } // 添加序号列 if (!HiddenGridIndex) { var gridIndex = new LayuiColumn() { Type = LayuiColumnTypeEnum.Numbers, Rowspan = maxDepth }; tempCols.Add(gridIndex); } var nextCols = new List <IGridColumn <TopBasePoco> >();// 下一级列头 foreach (var item in rawCols) { var tempCol = new LayuiColumn() { Title = item.Title, Field = item.Field, Width = item.Width, Sort = item.Sort, Fixed = item.Fixed, Align = item.Align, UnResize = item.UnResize, Hide = item.Hide, //Style = "height:auto !important;white-space:normal !important" //EditType = item.EditType }; switch (item.ColumnType) { case GridColumnTypeEnum.Space: tempCol.Type = LayuiColumnTypeEnum.Space; break; case GridColumnTypeEnum.Action: tempCol.Toolbar = $"#{ToolBarId}"; break; default: break; } if (item.Children != null && item.Children.Count() > 0) { tempCol.Colspan = item.ChildrenLength; } if (maxDepth > 1 && (item.Children == null || item.Children.Count() == 0)) { tempCol.Rowspan = maxDepth; } tempCols.Add(tempCol); if (item.Children != null && item.Children.Count() > 0) { nextCols.AddRange(item.Children); } } if (nextCols.Count > 0) { CalcChildCol(layuiCols, nextCols, maxDepth, 1); } #endregion #region 处理 DataTable 操作按钮 var actionCol = ListVM?.GridActions; var rowBtnStrBuilder = new StringBuilder(); // Grid 行内按钮 var toolBarBtnStrBuilder = new StringBuilder(); // Grid 工具条按钮 var gridBtnEventStrBuilder = new StringBuilder(); // Grid 按钮事件 if (actionCol != null && actionCol.Count > 0) { var vm = Vm.Model as BaseVM; foreach (var item in actionCol) { AddSubButton(vmQualifiedName, rowBtnStrBuilder, toolBarBtnStrBuilder, gridBtnEventStrBuilder, vm, item); } } #endregion #region DataTable var vmName = string.Empty; if (VMType != null) { var vmQualifiedName1 = VMType.AssemblyQualifiedName; vmName = vmQualifiedName1.Substring(0, vmQualifiedName1.LastIndexOf(", Version=")); } output.PostElement.AppendHtml($@" <script> var table = layui.table; /* 暂时解决 layui table首次及table.reload()无loading的bug */ var layer = layui.layer; var msg = layer.msg('数据请求中', {{ icon: 16, time: -1, anim: -1, fixed: false }}) /* 暂时解决 layui table首次及table.reload()无loading的bug */ var {Id}option = {{ elem: '#{Id}' ,id: '{Id}' ,autoSort: false {(string.IsNullOrEmpty(Url) ? string.Empty : $",url: '{Url}'")} {(Filter == null || Filter.Count == 0 ? string.Empty : $",where: {JsonConvert.SerializeObject(Filter)}")} {(Method == null ? ",method:'post'" : $",method: '{Method.Value.ToString().ToLower()}'")} {(UseLocalData ? $",data: {ListVM.GetDataJson()}" : string.Empty)} {(!Loading.HasValue ? string.Empty : $",loading: {Loading.Value.ToString().ToLower()}")} ,request: {JsonConvert.SerializeObject(request)} ,response: {JsonConvert.SerializeObject(response)} {(Page ?? true ? ",page:true" : ",page:{layout:['count']}")} ,limit: {(Page ?? true ? $"{Limit ?? 50}" : $"{(UseLocalData ? ListVM.GetEntityList().Count().ToString() : "0")}")} {(Page ?? true ? (Limits == null || Limits.Length == 0 ? ",limits:[10,20,50,80,100,150,200]" : $",limits:{JsonConvert.SerializeObject(Limits)}") : string.Empty)} {(!Width.HasValue ? string.Empty : $",width: {Width.Value}")} {(!Height.HasValue ? string.Empty : (Height.Value >= 0 ? $",height: {Height.Value}" : $",height: 'full{Height.Value}'"))} ,cols:{JsonConvert.SerializeObject(layuiCols, _jsonSerializerSettings)} {(!Skin.HasValue ? string.Empty : $",skin: '{Skin.Value.ToString().ToLower()}'")} {(!Even.HasValue ? ",even: true" : $",even: {Even.Value.ToString().ToLower()}")} {(!Size.HasValue ? string.Empty : $",size: '{Size.Value.ToString().ToLower()}'")} ,done: function(res,curr,count){{layer.close(msg); var tab = $('#{Id} + .layui-table-view');tab.find('table').css('border-collapse','separate'); {(Height == null ? $"tab.css('overflow','hidden').addClass('donotuse_fill donotuse_pdiv');tab.children('.layui-table-box').addClass('donotuse_fill donotuse_pdiv').css('height','100px');tab.find('.layui-table-main').addClass('donotuse_fill');tab.find('.layui-table-header').css('min-height','40px');ff.triggerResize();" : string.Empty)} {(MultiLine == true ? $"tab.find('.layui-table-cell').css('height','auto').css('white-space','normal');" : string.Empty)} {(string.IsNullOrEmpty(DoneFunc) ? string.Empty : $"{DoneFunc}(res,curr,count)")}
public override void OnActionExecuting(ActionExecutingContext context) { var controller = context.Controller as IBaseController; if (controller == null) { base.OnActionExecuting(context); return; } if (controller.ConfigInfo.IsQuickDebug && controller is BaseApiController) { base.OnActionExecuting(context); return; } ControllerActionDescriptor ad = context.ActionDescriptor as ControllerActionDescriptor; var lg = GlobalServices.GetRequiredService <LinkGenerator>(); string u = null; if (ad.Parameters.Any(x => x.Name.ToLower() == "id")) { u = lg.GetPathByAction(ad.ActionName, ad.ControllerName, new { area = context.RouteData.Values["area"], id = 0 }); } else { u = lg.GetPathByAction(ad.ActionName, ad.ControllerName, new { area = context.RouteData.Values["area"] }); } if (u != null && u.EndsWith("/0")) { u = u.Substring(0, u.Length - 2); if (controller is BaseApiController) { u = u + "/{id}"; } } controller.BaseUrl = u + context.HttpContext.Request.QueryString.ToUriComponent();; //如果是QuickDebug模式,或者Action或Controller上有AllRightsAttribute标记都不需要判断权限 //如果用户登录信息为空,也不需要判断权限,BaseController中会对没有登录的用户做其他处理 var isPublic = ad.MethodInfo.IsDefined(typeof(PublicAttribute), false) || ad.ControllerTypeInfo.IsDefined(typeof(PublicAttribute), false); if (!isPublic) { isPublic = ad.MethodInfo.IsDefined(typeof(AllowAnonymousAttribute), false) || ad.ControllerTypeInfo.IsDefined(typeof(AllowAnonymousAttribute), false); } var isAllRights = ad.MethodInfo.IsDefined(typeof(AllRightsAttribute), false) || ad.ControllerTypeInfo.IsDefined(typeof(AllRightsAttribute), false); var isDebug = ad.MethodInfo.IsDefined(typeof(DebugOnlyAttribute), false) || ad.ControllerTypeInfo.IsDefined(typeof(DebugOnlyAttribute), false); if (controller.ConfigInfo.IsFilePublic == true) { if (ad.ControllerName == "_Framework" && (ad.MethodInfo.Name == "GetFile" || ad.MethodInfo.Name == "ViewFile")) { isPublic = true; } } if (isDebug) { if (controller.ConfigInfo.IsQuickDebug) { base.OnActionExecuting(context); } else { if (controller is BaseController c) { context.Result = c.Content(Program._localizer["DebugOnly"]); } else if (controller is ControllerBase c2) { context.Result = c2.BadRequest(Program._localizer["DebugOnly"]); } } return; } if (isPublic == true) { base.OnActionExecuting(context); return; } if (controller.LoginUserInfo == null) { context.HttpContext.ChallengeAsync().Wait(); } else { if (isAllRights == false) { bool canAccess = controller.LoginUserInfo.IsAccessable(controller.BaseUrl); if (canAccess == false && controller.ConfigInfo.IsQuickDebug == false) { if (controller is ControllerBase ctrl) { var authenticationSchemes = new List <string>(); if (ad.MethodInfo.IsDefined(typeof(AuthorizeAttribute), false)) { var authorizeAttr = ad.MethodInfo.GetCustomAttributes(typeof(AuthorizeAttribute), false).FirstOrDefault() as AuthorizeAttribute; if (authorizeAttr != null) { authenticationSchemes = authorizeAttr.AuthenticationSchemes.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList(); } } else if (ad.ControllerTypeInfo.IsDefined(typeof(AuthorizeAttribute), false)) { var authorizeAttr = ad.ControllerTypeInfo.GetCustomAttributes(typeof(AuthorizeAttribute), false).FirstOrDefault() as AuthorizeAttribute; if (authorizeAttr != null) { authenticationSchemes = authorizeAttr.AuthenticationSchemes.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList(); } } if (ctrl.HttpContext.Request.Headers.ContainsKey("Authorization") && authenticationSchemes.Contains(JwtBearerDefaults.AuthenticationScheme)) { context.Result = ctrl.Forbid(JwtBearerDefaults.AuthenticationScheme); } else if (ctrl.HttpContext.Request.Cookies.ContainsKey(CookieAuthenticationDefaults.CookiePrefix + AuthConstants.CookieAuthName) && authenticationSchemes.Contains(CookieAuthenticationDefaults.AuthenticationScheme)) { throw new Exception(Program._localizer["NoPrivilege"]); } else { throw new Exception(Program._localizer["NoPrivilege"]); } } } } } base.OnActionExecuting(context); }