diff --git a/Yi.Framework.Net6/.editorconfig b/Yi.Framework.Net6/.editorconfig new file mode 100644 index 00000000..4de968e1 --- /dev/null +++ b/Yi.Framework.Net6/.editorconfig @@ -0,0 +1,4 @@ +[*.cs] + +# SYSLIB0014: 类型或成员已过时 +dotnet_diagnostic.SYSLIB0014.severity = none diff --git a/Yi.Framework.Net6/Yi.Framework.ApiMicroservice/Log4net.config b/Yi.Framework.Net6/Yi.Framework.ApiMicroservice/Config/Log4net.config similarity index 100% rename from Yi.Framework.Net6/Yi.Framework.ApiMicroservice/Log4net.config rename to Yi.Framework.Net6/Yi.Framework.ApiMicroservice/Config/Log4net.config diff --git a/Yi.Framework.Net6/Yi.Framework.OcelotGateway/SwaggerDoc.xml b/Yi.Framework.Net6/Yi.Framework.ApiMicroservice/Config/SwaggerDoc.xml similarity index 65% rename from Yi.Framework.Net6/Yi.Framework.OcelotGateway/SwaggerDoc.xml rename to Yi.Framework.Net6/Yi.Framework.ApiMicroservice/Config/SwaggerDoc.xml index 16f3de1b..1f59e900 100644 --- a/Yi.Framework.Net6/Yi.Framework.OcelotGateway/SwaggerDoc.xml +++ b/Yi.Framework.Net6/Yi.Framework.ApiMicroservice/Config/SwaggerDoc.xml @@ -1,7 +1,7 @@ - Yi.Framework.OcelotGateway + Yi.Framework.ApiMicroservice diff --git a/Yi.Framework.Net6/Yi.Framework.ApiMicroservice/Controllers/AccountController.cs b/Yi.Framework.Net6/Yi.Framework.ApiMicroservice/Controllers/AccountController.cs deleted file mode 100644 index 6d815d82..00000000 --- a/Yi.Framework.Net6/Yi.Framework.ApiMicroservice/Controllers/AccountController.cs +++ /dev/null @@ -1,228 +0,0 @@ -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc; -using Microsoft.Extensions.Logging; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using Yi.Framework.Common; -using Yi.Framework.Common.Const; -using Yi.Framework.Common.Helper; -using Yi.Framework.Common.Models; -using Yi.Framework.Common.QueueModel; -using Yi.Framework.Core; -using Yi.Framework.DTOModel; -using Yi.Framework.Interface; -using Yi.Framework.Model.Models; -using Yi.Framework.WebCore; -using Yi.Framework.WebCore.AuthorizationPolicy; -using Yi.Framework.WebCore.Mapper; - -namespace Yi.Framework.ApiMicroservice.Controllers -{ - [ApiController] - [Route("api/[controller]/[action]")] - public class AccountController : Controller - { - private readonly ILogger _logger; - - private IUserService _userService; - private IMenuService _menuService; - private RabbitMQInvoker _rabbitMQInvoker; - private CacheClientDB _cacheClientDB; - private IRoleService _roleService; - private IHttpContextAccessor _httpContext; - public AccountController(ILogger logger, IUserService userService, IMenuService menuService, RabbitMQInvoker rabbitMQInvoker, CacheClientDB cacheClientDB, IRoleService roleService, IHttpContextAccessor httpContext) - { - _logger = logger; - _userService = userService; - _menuService = menuService; - _rabbitMQInvoker = rabbitMQInvoker; - _cacheClientDB = cacheClientDB; - _roleService = roleService; - _httpContext = httpContext; - } - - - /// - /// 登录方法,要返回data:{user,token} token - /// - /// - /// - [HttpPost] - public async Task Login(loginDto login) - { - var _user = MapperHelper.Map(login); - var user_data = await _userService.Login(_user); - if (user_data == null) - { - return Result.Error("该用户不存在"); - } - var menuList = await _menuService.GetTopMenuByUserId(user_data.id); - if (user_data != null) - { - var token = MakeJwt.app(new jwtUser() { user = user_data, menuIds = menuList }); - JobModel.visitNum += 1; - //同时要将api路径放置到redis中 - var menuDto = MapperHelper.MapList(menuList); - _userService.SaveUserApi(user_data.id, menuDto); - return Result.Success().SetData(new { user = new { user_data.id, user_data.username, user_data.introduction, user_data.icon, user_data.nick }, token }); - } - return Result.Error(); - } - - /// - /// 不用写,单纯制作日志 - /// - /// - - [HttpPost] - public Result Logout() - { - return Result.Success(); - } - - /// - /// code为验证码,从redis中判断一下code是否正确 - /// - /// - /// - /// - [HttpPost] - public async Task Register(user _user, string code) - { - _user.username = _user.username.Trim(); - if (string.IsNullOrEmpty(_user.username)) - code = code.Trim(); - - string trueCode = _cacheClientDB.Get(RedisConst.keyCode + _user.phone); - if (code == trueCode) - { - //设置默认头像 - var setting = JsonHelper.StrToObj(_cacheClientDB.Get(RedisConst.key)); - _user.icon = setting.InitIcon; - _user.ip = _httpContext.HttpContext?.Request.Headers["X-Real-IP"].FirstOrDefault();//通过上下文获取ip - //设置默认角色 - if (string.IsNullOrEmpty(setting.InitRole)) - { - return Result.Error("无默认角色,请初始化数据库"); - } - _user.roles = new List(); - _user.roles.Add(await _roleService.GetEntity(u => u.role_name == setting.InitRole)); - await _userService.Register(_user); - - return Result.Success("恭喜,你已加入我们!"); - } - return Result.Error("验证码有误,请重新输入!"); - } - - - /// - /// 发送短信,需要将生成的sms+code存入redis - /// - /// - /// - [HttpPost] - public async Task SendSMS(string SMSAddress) - { - if (string.IsNullOrEmpty(SMSAddress)) - { - return Result.Error("请输入电话号码"); - } - SMSAddress = SMSAddress.Trim(); - if (!await _userService.PhoneIsExsit(SMSAddress)) - { - SMSQueueModel sMSQueueModel = new SMSQueueModel(); - sMSQueueModel.phone = SMSAddress; - sMSQueueModel.code = RandomHelper.GenerateCheckCodeNum(6); - - //10分钟过期 - _cacheClientDB.Set(RedisConst.keyCode + sMSQueueModel.phone, sMSQueueModel.code, TimeSpan.FromMinutes(10)); - - _rabbitMQInvoker.Send(new Common.IOCOptions.RabbitMQConsumerModel() { ExchangeName = RabbitConst.SMS_Exchange, QueueName = RabbitConst.SMS_Queue_Send }, JsonHelper.ObjToStr(sMSQueueModel)); - return Result.Success("发送短信成功,10分钟后过期,请留意短信接收"); - } - return Result.Error("该号码已被注册"); - } - - /// - /// 发送邮箱,需要先到数据库判断该邮箱是否被人注册过,到userservice写mail_exist方法,还有接口别忘了。 - /// - /// - /// - [HttpPost]//邮箱验证 - public async Task Email(string emailAddress) - { - emailAddress = emailAddress.Trim().ToLower(); - //先判断邮箱是否被注册使用过,如果被使用过,便不让操作 - if (!await _userService.EmailIsExsit(emailAddress)) - { - string code = RandomHelper.GenerateRandomLetter(6); - code = code.ToUpper();//全部转为大写 - EmailHelper.sendMail(code, emailAddress); - - //我要把邮箱和对应的code加进到数据库,还有申请时间 - //设置10分钟过期 - //set不存在便添加,如果存在便替换 - //CacheHelper.SetCache(emailAddress, code, TimeSpan.FromSeconds(10)); - - return Result.Success("发送邮件成功,请查看邮箱(可能在垃圾箱)"); - } - else - { - return Result.Error("该邮箱已被注册"); - } - // 邮箱和验证码都要被记住,然后注册时候比对邮箱和验证码是不是都和现在生成的一样 - } - /// - /// 修改密码 - /// - /// - /// - [HttpPut] - [Authorize] - public async Task ChangePassword(ChangePwdDto pwdDto) - { - var user_data = await _userService.GetUserById(pwdDto.user.id); - string msg = "修改成功"; - if (!string.IsNullOrEmpty(pwdDto.newPassword)) - { - if (user_data.password == pwdDto.user.password) - { - - user_data.password = pwdDto.newPassword; - user_data.phone = pwdDto.user.phone; - user_data.introduction = pwdDto.user.introduction; - user_data.email = pwdDto.user.email; - user_data.age = pwdDto.user.age; - user_data.address = pwdDto.user.address; - user_data.nick = pwdDto.user.nick; - - - await _userService.UpdateAsync(user_data); - user_data.password = null; - return Result.Success(msg); - } - else - { - msg = "密码错误"; - return Result.Error(msg); - } - } - - user_data.phone = pwdDto.user.phone; - user_data.introduction = pwdDto.user.introduction; - user_data.email = pwdDto.user.email; - user_data.age = pwdDto.user.age; - user_data.address = pwdDto.user.address; - user_data.nick = pwdDto.user.nick; - - await _userService.UpdateAsync(user_data); - - - return Result.Success(msg); - } - - } -} \ No newline at end of file diff --git a/Yi.Framework.Net6/Yi.Framework.ApiMicroservice/Controllers/FileController.cs b/Yi.Framework.Net6/Yi.Framework.ApiMicroservice/Controllers/FileController.cs deleted file mode 100644 index 8dcae4c7..00000000 --- a/Yi.Framework.Net6/Yi.Framework.ApiMicroservice/Controllers/FileController.cs +++ /dev/null @@ -1,92 +0,0 @@ -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc; -using Microsoft.Extensions.Hosting; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Threading.Tasks; -using Yi.Framework.Common.Models; -using Yi.Framework.Interface; -using Yi.Framework.WebCore; - -namespace Yi.Framework.ApiMicroservice.Controllers -{ - [Route("api/[controller]/[action]")] - [ApiController] - public class FileController : ControllerBase - { - private IUserService _userService; - private readonly IHostEnvironment _env; - public FileController(IUserService userService, IHostEnvironment env) - { - _userService = userService; - _env = env; - } - [HttpPost] - [Authorize] - public async Task EditIcon(IFormFile file) - { - try - { - var _user = HttpContext.GetCurrentUserInfo(); - var user_data = await _userService.GetUserById(_user.id); - var type = "image"; - var filename = await Upload(type, file); - user_data.icon = filename; - await _userService.UpdateAsync(user_data); - return Result.Success(); - } - catch - { - return Result.Error(); - } - } - - [Route("/api/{type}/{fileName}")] - [HttpGet] - public IActionResult Get(string type, string fileName) - { - try - { - var path = Path.Combine($"wwwroot/{type}", fileName); - var stream = System.IO.File.OpenRead(path); - var MimeType = Common.Helper.MimeHelper.GetMimeMapping(fileName); - return new FileStreamResult(stream, MimeType); - } - catch - { - return new NotFoundResult(); - } - } - - /// - /// 该方法不对外暴露 - /// - /// - /// - /// - private async Task Upload(string type, IFormFile file) - { - string filename = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName); - using (var stream = new FileStream(Path.Combine($"wwwroot/{type}", filename), FileMode.CreateNew, FileAccess.Write)) - { - await file.CopyToAsync(stream); - } - - return filename; - } - - [HttpGet] - public async Task ExportFile() - { - var userdata = await _userService.GetAllEntitiesTrueAsync(); - var userList = userdata.ToList(); - List header = new() { "用户", "密码", "头像", "昵称", "邮箱", "ip", "年龄", "个人介绍", "地址", "手机", "角色" }; - var filename = Common.Helper.ExcelHelper.CreateExcelFromList(userList, header, _env.ContentRootPath.ToString()); - var MimeType = Common.Helper.MimeHelper.GetMimeMapping(filename); - return new FileStreamResult(new FileStream(Path.Combine(_env.ContentRootPath+@"/wwwroot/Excel", filename), FileMode.Open),MimeType); - } - } -} diff --git a/Yi.Framework.Net6/Yi.Framework.ApiMicroservice/Controllers/JobController.cs b/Yi.Framework.Net6/Yi.Framework.ApiMicroservice/Controllers/JobController.cs deleted file mode 100644 index a7d0f35d..00000000 --- a/Yi.Framework.Net6/Yi.Framework.ApiMicroservice/Controllers/JobController.cs +++ /dev/null @@ -1,104 +0,0 @@ -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; -using Microsoft.Extensions.Logging; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using Yi.Framework.Common; -using Yi.Framework.Common.Const; -using Yi.Framework.Common.Helper; -using Yi.Framework.Common.Models; -using Yi.Framework.Core; -using Yi.Framework.DTOModel; -using Yi.Framework.Interface; -using Yi.Framework.Model.Models; - -namespace Yi.Framework.ApiMicroservice.Controllers -{ - [ApiController] - [Route("api/[controller]/[action]")] - public class JobController : Controller - { - private readonly ILogger _logger; - private QuartzInvoker _quartzInvoker; - public JobController(ILogger logger,QuartzInvoker quartzInvoker) - { - _logger = logger; - _quartzInvoker = quartzInvoker; - } - - /// - /// - /// - /// - [HttpPost] - public async Task startJob() - { - //任务1 - //await _quartzInvoker.start("*/1 * * * * ? ", new Quartz.JobKey("test", "my"), "VisitJob"); - - //任务2 - Dictionary data = new Dictionary() - { - {JobConst.method,"get" }, - {JobConst.url,"https://www.baidu.com" } - }; - await _quartzInvoker.start("*/5 * * * * ?", new Quartz.JobKey("test", "my"), "Yi.Framework.Job", "HttpJob",data: data); - return Result.Success(); - } - - /// - /// - /// - /// - [HttpGet] - public async Task getRunJobList() - { - return Result.Success().SetData(await _quartzInvoker.getRunJobList()); - } - - /// - /// - /// - /// - [HttpGet] - public Result getJobClass() - { - return Result.Success().SetData(_quartzInvoker.getJobClassList()); - } - - /// - /// - /// - /// - [HttpPut] - public async Task stopJob() - { - await _quartzInvoker.Stop(new Quartz.JobKey("test", "my")); - return Result.Success(); - } - - /// - /// - /// - /// - [HttpDelete] - public async Task DeleteJob() - { - await _quartzInvoker.Delete(new Quartz.JobKey("test", "my")); - return Result.Success(); - } - - /// - /// - /// - /// - [HttpPut] - public async Task ResumeJob() - { - await _quartzInvoker.Resume(new Quartz.JobKey("test", "my")); - return Result.Success(); - } - } -} \ No newline at end of file diff --git a/Yi.Framework.Net6/Yi.Framework.ApiMicroservice/Controllers/MenuController.cs b/Yi.Framework.Net6/Yi.Framework.ApiMicroservice/Controllers/MenuController.cs deleted file mode 100644 index 7bb08bd4..00000000 --- a/Yi.Framework.Net6/Yi.Framework.ApiMicroservice/Controllers/MenuController.cs +++ /dev/null @@ -1,114 +0,0 @@ -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using Yi.Framework.Common.Models; -using Yi.Framework.DTOModel; -using Yi.Framework.Interface; -using Yi.Framework.Model.Models; -using Yi.Framework.WebCore; - -namespace Yi.Framework.ApiMicroservice.Controllers -{ - [Route("api/[controller]/[action]")] - [ApiController] - [Authorize] - public class MenuController : ControllerBase - { - private IMenuService _menuService; - private IUserService _userService; - public MenuController(IMenuService menuService,IUserService userService) - { - _menuService = menuService; - _userService = userService; - } - /// - /// 这个是要递归的,但是要过滤掉删除的,所以,可以写一个通用过滤掉删除的方法 - /// - /// - [HttpGet] - public async Task GetMenuInMould() - { - return Result.Success().SetData(await _menuService.GetMenuInMould()); - } - - /// - /// 更 - /// - /// - /// - [HttpPut] - public async Task UpdateMenu(menu _menu) - { - await _menuService.UpdateAsync(_menu); - return Result.Success(); - - } - - /// - /// 删 - /// - /// - /// - [HttpDelete] - public async Task DelListMenu(List _ids) - { - await _menuService.DelListByUpdateAsync(_ids); - return Result.Success(); - } - - /// - /// 增 - /// 现在,top菜单只允许为一个 - /// - /// - /// - [HttpPost] - public async Task AddTopMenu(menu _menu) - { - await _menuService.AddTopMenu(_menu); - return Result.Success(); - } - - /// - /// 给一个菜单设置一个接口,Id1为菜单id,Id2为接口id - /// 用于给菜单设置接口 - /// - /// - /// - [HttpPost] - public async Task SetMouldByMenu(IdDto idDto) - { - await _menuService.SetMouldByMenu(idDto.id1, idDto.id2); - return Result.Success(); - } - - - /// - /// 给一个菜单添加子节点(注意:添加,不是覆盖) - /// - /// - /// - [HttpPost] - public async Task AddChildrenMenu(ChildrenDto childrenDto) - { - await _menuService.AddChildrenMenu(childrenDto.parentId, childrenDto.data); - return Result.Success(); - } - - /// - /// 获取用户的目录菜单,不包含接口 - /// 用于账户信息页面,显示这个用户有哪些菜单,需要并列 - /// - /// - [HttpGet] - public async Task GetTopMenusByHttpUser() - { - var menuIds = _userService.GetCurrentMenuInfo(HttpContext.GetCurrentUserInfo().id); - return Result.Success().SetData(await _menuService.GetTopMenusByTopMenuIds(menuIds)); - } - } -} diff --git a/Yi.Framework.Net6/Yi.Framework.ApiMicroservice/Controllers/MouldController.cs b/Yi.Framework.Net6/Yi.Framework.ApiMicroservice/Controllers/MouldController.cs deleted file mode 100644 index 7c0ee94a..00000000 --- a/Yi.Framework.Net6/Yi.Framework.ApiMicroservice/Controllers/MouldController.cs +++ /dev/null @@ -1,69 +0,0 @@ -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using Yi.Framework.Common.Models; -using Yi.Framework.Interface; -using Yi.Framework.Model.Models; - -namespace Yi.Framework.ApiMicroservice.Controllers -{ - [Route("api/[controller]/[action]")] - [ApiController] - [Authorize] - public class MouldController : ControllerBase - { - private IMouldService _mouldService; - public MouldController(IMouldService mouldService) - { - _mouldService = mouldService; - } - [HttpGet] - public async Task GetMould() - { - return Result.Success().SetData(await _mouldService.GetAllEntitiesTrueAsync()); - } - - /// - /// 更 - /// - /// - /// - [HttpPut] - public async Task UpdateMould(mould _mould) - { - await _mouldService.UpdateAsync(_mould); - return Result.Success(); - - } - - /// - /// 删 - /// - /// - /// - [HttpDelete] - public async Task DelListMould(List _ids) - { - await _mouldService.DelListByUpdateAsync(_ids); - return Result.Success(); - } - - /// - /// 增 - /// - /// - /// - [HttpPost] - public async Task AddMould(mould _mould) - { - await _mouldService.AddAsync(_mould); - return Result.Success(); - } - - - } -} diff --git a/Yi.Framework.Net6/Yi.Framework.ApiMicroservice/Controllers/RoleController.cs b/Yi.Framework.Net6/Yi.Framework.ApiMicroservice/Controllers/RoleController.cs deleted file mode 100644 index 46fe2cc3..00000000 --- a/Yi.Framework.Net6/Yi.Framework.ApiMicroservice/Controllers/RoleController.cs +++ /dev/null @@ -1,106 +0,0 @@ -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Threading.Tasks; -using Yi.Framework.Common.Models; -using Yi.Framework.DTOModel; -using Yi.Framework.Interface; -using Yi.Framework.Model.Models; -using Yi.Framework.WebCore; - -namespace Yi.Framework.ApiMicroservice.Controllers -{ - [Route("api/[controller]/[action]")] - [ApiController] - [Authorize] - public class RoleController : ControllerBase - { - private IRoleService _roleService; - public RoleController(IRoleService roleService) - { - _roleService = roleService; - } - [HttpGet] - public async Task GetRole() - { - return Result.Success().SetData(await _roleService.GetAllEntitiesTrueAsync()); - } - - - /// - /// 更 - /// - /// - /// - [HttpPut] - public async Task UpdateRole(role _role) - { - await _roleService.UpdateAsync(_role); - return Result.Success(); - - } - - /// - /// 删 - /// - /// - /// - [HttpDelete] - public async Task DelListRole(List _ids) - { - await _roleService.DelListByUpdateAsync(_ids); - return Result.Success(); - } - - /// - /// 增 - /// - /// - /// - [HttpPost] - public async Task AddRole(role _role) - { - await _roleService.AddAsync(_role); - return Result.Success(); - } - - /// - /// 根据用户id得到该用户有哪些角色 - /// 用于显示用户详情中的角色说明 - /// - /// - [HttpGet] - public async Task GetRolesByUserId(int userId) - { - - return Result.Success().SetData(await _roleService.GetRolesByUserId(userId)); - } - /// - /// 给角色设置菜单,多个角色与多个菜单,让每一个角色都设置,ids1为角色,ids2为菜单 - /// 用于设置角色 - /// - /// - /// - [HttpPost] - public async Task SetMenuByRole(IdsListDto idsListDto) - { - await _roleService.SetMenusByRolesId(idsListDto.ids2, idsListDto.ids1); - return Result.Success(); - } - /// - /// 用于给角色设置菜单的时候,点击一个角色,显示这个角色拥有的并列的菜单 - /// - /// - /// - [HttpGet] - public async Task GetTopMenusByRoleId(int roleId) - { - - return Result.Success().SetData(await _roleService.GetTopMenusByRoleId(roleId) ); ; - } - } -} diff --git a/Yi.Framework.Net6/Yi.Framework.ApiMicroservice/Controllers/SettingController.cs b/Yi.Framework.Net6/Yi.Framework.ApiMicroservice/Controllers/SettingController.cs deleted file mode 100644 index d101bc9d..00000000 --- a/Yi.Framework.Net6/Yi.Framework.ApiMicroservice/Controllers/SettingController.cs +++ /dev/null @@ -1,60 +0,0 @@ -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; -using Microsoft.Extensions.Logging; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using Yi.Framework.Common.Const; -using Yi.Framework.Common.Models; -using Yi.Framework.Core; -using Yi.Framework.DTOModel; -using Yi.Framework.Interface; -using Yi.Framework.Model.Models; -using Yi.Framework.WebCore; - -namespace Yi.Framework.ApiMicroservice.Controllers -{ - [ApiController] - [Route("api/[controller]/[action]")] - [Authorize] - public class SettingController : ControllerBase - { - private readonly ILogger _logger; - private readonly CacheClientDB _cacheClientDB; - - public SettingController(ILogger logger, CacheClientDB cacheClientDB) - { - _logger = logger; - _cacheClientDB = cacheClientDB; - } - - - - /// - /// 查 - /// - /// - [HttpGet] - public Result GetSetting() - { - var setDto = Common.Helper.JsonHelper.StrToObj(_cacheClientDB.Get(RedisConst.key)); - return Result.Success().SetData( setDto); - } - - /// - /// 更 - /// - /// - /// - [HttpPut] - public Result UpdateSetting(SettingDto settingDto) - { - var setDto = Common.Helper.JsonHelper.ObjToStr(settingDto); - - _cacheClientDB.Set(RedisConst.key, setDto); - return Result.Success(); - - } - } -} diff --git a/Yi.Framework.Net6/Yi.Framework.ApiMicroservice/Controllers/UserController.cs b/Yi.Framework.Net6/Yi.Framework.ApiMicroservice/Controllers/UserController.cs index 24a3dc96..3bd4adb2 100644 --- a/Yi.Framework.Net6/Yi.Framework.ApiMicroservice/Controllers/UserController.cs +++ b/Yi.Framework.Net6/Yi.Framework.ApiMicroservice/Controllers/UserController.cs @@ -6,7 +6,6 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Yi.Framework.Common.Models; -using Yi.Framework.DTOModel; using Yi.Framework.Interface; using Yi.Framework.Model.Models; using Yi.Framework.WebCore; @@ -21,133 +20,17 @@ namespace Yi.Framework.ApiMicroservice.Controllers { private readonly ILogger _logger; - private IUserService _userService; - public UserController(ILogger logger, IUserService userService) + private IUserService _iUserService; + public UserController(ILogger logger, IUserService iUserService) { _logger = logger; - _userService = userService; + _iUserService = iUserService; } - /// - /// 查 - /// - /// - - [Authorize(PolicyName.Menu)] [HttpGet] - public async Task GetUser() + public async Task Get() { - return Result.Success().SetData(await _userService.GetAllEntitiesTrueAsync()); + return Result.Success().SetData(await _iUserService.GetListAsync()); } - - /// - /// 更 - /// - /// - /// - [HttpPut] - [Authorize(PolicyName.Menu)] - public async Task UpdateUser(user _user) - { - await _userService.UpdateAsync(_user); - return Result.Success(); - - } - - /// - /// 删 - /// - /// - /// - [HttpDelete] - [Authorize(PolicyName.Menu)] - public async Task DelListUser(List _ids) - { - await _userService.DelListByUpdateAsync(_ids); - return Result.Success(); - } - - /// - /// 增 - /// - /// - /// - [HttpPost] - [Authorize(PolicyName.Menu)] - public async Task AddUser(user _user) - { - await _userService.AddAsync(_user); - return Result.Success(); - } - - - /// - /// SetRoleByUser - /// 给多个用户设置多个角色,ids有用户id与 角色列表ids,多对多,ids1用户,ids2为角色 - /// 用户设置给用户设置角色 - /// - /// - /// - [HttpPost] - public async Task SetRoleByUser(IdsListDto idsListDto) - { - await _userService.SetRoleByUser(idsListDto.ids2, idsListDto.ids1); - return Result.Success(); - } - - /// - /// 根据http上下文的用户得到该用户信息,关联角色 - /// 用于显示账号信息页中的用户信息和角色信息 - /// - /// - [HttpGet] - public async Task GetUserInRolesByHttpUser() - { - var _user = HttpContext.GetCurrentUserInfo(); - return Result.Success().SetData( await _userService.GetUserInRolesByHttpUser(_user.id)); - } - - /// - /// 得到登录用户的递归菜单,放到导航栏 - /// 用户放到导航栏中 - /// - /// - [HttpGet] - public async Task GetMenuByHttpUser() - { - var allMenuIds= _userService.GetCurrentMenuInfo(HttpContext.GetCurrentUserInfo().id); - return Result.Success().SetData(await _userService.GetMenuByHttpUser(allMenuIds)); - } - - /// - /// 得到请求模型 - /// - /// - /// - [HttpGet] - public async Task GetAxiosByRouter(string router) - { - var _user = HttpContext.GetCurrentUserInfo(); - var menuIds = _userService.GetCurrentMenuInfo(_user.id); - if (menuIds == null) - { - return Result.Error(); - } - var menuList= await _userService.GetAxiosByRouter(router, menuIds); - AxiosUrlsModel urlsModel = new(); - menuList.ForEach(u => - { - switch (u.menu_name) - { - case "get":urlsModel.get = u.mould.url;break; - case "del": urlsModel.del = u.mould.url; break; - case "add": urlsModel.add = u.mould.url; break; - case "update": urlsModel.update = u.mould.url; break; - } - }); - - return Result.Success().SetData(urlsModel); - } - } } diff --git a/Yi.Framework.Net6/Yi.Framework.ApiMicroservice/Program.cs b/Yi.Framework.Net6/Yi.Framework.ApiMicroservice/Program.cs index a3407a57..0204b559 100644 --- a/Yi.Framework.Net6/Yi.Framework.ApiMicroservice/Program.cs +++ b/Yi.Framework.Net6/Yi.Framework.ApiMicroservice/Program.cs @@ -1,10 +1,10 @@ using Autofac.Extensions.DependencyInjection; using Yi.Framework.WebCore.BuilderExtend; using Yi.Framework.Core; -using Yi.Framework.Model.ModelFactory; using Yi.Framework.WebCore.MiddlewareExtend; using Yi.Framework.WebCore.Utility; using Autofac; +using Yi.Framework.Common.Models; var builder = WebApplication.CreateBuilder(args); @@ -70,10 +70,6 @@ builder.Services.AddJwtService(); #endregion builder.Services.AddAuthorizationService(); #region -//ݿ -#endregion -builder.Services.AddDbService(); -#region //Redis #endregion builder.Services.AddRedisService(); @@ -95,6 +91,11 @@ builder.Services.AddSMSService(); builder.Services.AddCAPService(); //----------------------------------------------------------------------------------------------------------- var app = builder.Build(); + +#region +// +#endregion +ServiceLocator.Instance = app.Services; //if (app.Environment.IsDevelopment()) { #region @@ -110,7 +111,6 @@ var app = builder.Build(); //ץȡע #endregion app.UseErrorHandlingService(); - #region //̬ļע #endregion @@ -144,10 +144,6 @@ app.UseAuthorization(); #endregion app.UseConsulService(); #region -//ݿע -#endregion -app.UseDbSeedInitService(app.Services.GetService()); -#region //redisע #endregion app.UseRedisSeedInitService(app.Services.GetService()); diff --git a/Yi.Framework.Net6/Yi.Framework.ApiMicroservice/SwaggerDoc.xml b/Yi.Framework.Net6/Yi.Framework.ApiMicroservice/SwaggerDoc.xml deleted file mode 100644 index 2eed29be..00000000 --- a/Yi.Framework.Net6/Yi.Framework.ApiMicroservice/SwaggerDoc.xml +++ /dev/null @@ -1,278 +0,0 @@ - - - - Yi.Framework.ApiMicroservice - - - - - 登录方法,要返回data:{user,token} token - - - - - - - 不用写,单纯制作日志 - - - - - - code为验证码,从redis中判断一下code是否正确 - - - - - - - - 发送短信,需要将生成的sms+code存入redis - - - - - - - 发送邮箱,需要先到数据库判断该邮箱是否被人注册过,到userservice写mail_exist方法,还有接口别忘了。 - - - - - - - 修改密码 - - - - - - - 该方法不对外暴露 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 这个是要递归的,但是要过滤掉删除的,所以,可以写一个通用过滤掉删除的方法 - - - - - - 更 - - - - - - - 删 - - - - - - - 增 - 现在,top菜单只允许为一个 - - - - - - - 给一个菜单设置一个接口,Id1为菜单id,Id2为接口id - 用于给菜单设置接口 - - - - - - - 给一个菜单添加子节点(注意:添加,不是覆盖) - - - - - - - 获取用户的目录菜单,不包含接口 - 用于账户信息页面,显示这个用户有哪些菜单,需要并列 - - - - - - 更 - - - - - - - 删 - - - - - - - 增 - - - - - - - 更 - - - - - - - 删 - - - - - - - 增 - - - - - - - 根据用户id得到该用户有哪些角色 - 用于显示用户详情中的角色说明 - - - - - - 给角色设置菜单,多个角色与多个菜单,让每一个角色都设置,ids1为角色,ids2为菜单 - 用于设置角色 - - - - - - - 用于给角色设置菜单的时候,点击一个角色,显示这个角色拥有的并列的菜单 - - - - - - - 查 - - - - - - 更 - - - - - - - 查 - - - - - - 更 - - - - - - - 删 - - - - - - - 增 - - - - - - - SetRoleByUser - 给多个用户设置多个角色,ids有用户id与 角色列表ids,多对多,ids1用户,ids2为角色 - 用户设置给用户设置角色 - - - - - - - 根据http上下文的用户得到该用户信息,关联角色 - 用于显示账号信息页中的用户信息和角色信息 - - - - - - 得到登录用户的递归菜单,放到导航栏 - 用户放到导航栏中 - - - - - - 得到请求模型 - - - - - - diff --git a/Yi.Framework.Net6/Yi.Framework.ApiMicroservice/Yi.Framework.ApiMicroservice.csproj b/Yi.Framework.Net6/Yi.Framework.ApiMicroservice/Yi.Framework.ApiMicroservice.csproj index 67e6d2f3..f721809f 100644 --- a/Yi.Framework.Net6/Yi.Framework.ApiMicroservice/Yi.Framework.ApiMicroservice.csproj +++ b/Yi.Framework.Net6/Yi.Framework.ApiMicroservice/Yi.Framework.ApiMicroservice.csproj @@ -9,7 +9,7 @@ - D:\CC.Yi\CC.Yi\Yi.Framework.Net6\Yi.Framework.ApiMicroservice\SwaggerDoc.xml + ./Config/SwaggerDoc.xml 1701;1702;CS1591 @@ -20,14 +20,6 @@ - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - diff --git a/Yi.Framework.Net6/Yi.Framework.Common/Helper/HttpHelper.cs b/Yi.Framework.Net6/Yi.Framework.Common/Helper/HttpHelper.cs index afc9c4d7..cd668621 100644 --- a/Yi.Framework.Net6/Yi.Framework.Common/Helper/HttpHelper.cs +++ b/Yi.Framework.Net6/Yi.Framework.Common/Helper/HttpHelper.cs @@ -14,7 +14,9 @@ namespace Yi.Framework.Common.Helper { public static string HttpGet(string Url, string postDataStr="") { +#pragma warning disable SYSLIB0014 // 类型或成员已过时 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr); +#pragma warning restore SYSLIB0014 // 类型或成员已过时 request.Method = "GET"; request.ContentType = "text/html;charset=UTF-8"; @@ -52,7 +54,9 @@ namespace Yi.Framework.Common.Helper public static string HttpPost(string Url, string postDataStr="") { CookieContainer cookie = new CookieContainer(); +#pragma warning disable SYSLIB0014 // 类型或成员已过时 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); +#pragma warning restore SYSLIB0014 // 类型或成员已过时 request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr); diff --git a/Yi.Framework.Net6/Yi.Framework.Common/Helper/MD5Hepler.cs b/Yi.Framework.Net6/Yi.Framework.Common/Helper/MD5Hepler.cs index 6eb53422..016d4e63 100644 --- a/Yi.Framework.Net6/Yi.Framework.Common/Helper/MD5Hepler.cs +++ b/Yi.Framework.Net6/Yi.Framework.Common/Helper/MD5Hepler.cs @@ -13,7 +13,9 @@ namespace Yi.Framework.Common.Helper /// public static string MD5Encrypt16(string password) { +#pragma warning disable SYSLIB0021 // 类型或成员已过时 var md5 = new MD5CryptoServiceProvider(); +#pragma warning restore SYSLIB0021 // 类型或成员已过时 string t2 = BitConverter.ToString(md5.ComputeHash(Encoding.Default.GetBytes(password)), 4, 8); t2 = t2.Replace("-", string.Empty); return t2; diff --git a/Yi.Framework.Net6/Yi.Framework.Common/IOCOptions/AuthorizationOptions.cs b/Yi.Framework.Net6/Yi.Framework.Common/IOCOptions/AuthorizationOptions.cs new file mode 100644 index 00000000..f204dd05 --- /dev/null +++ b/Yi.Framework.Net6/Yi.Framework.Common/IOCOptions/AuthorizationOptions.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Yi.Framework.Common.IOCOptions +{ + public class AuthorizationOptions + { + public string Refresh { get; set; } + public List WhiteList { get; set; } + public List AccountList { get; set; } + public List UserList { get; set; } + + public List TenantList { get; set; } + } +} diff --git a/Yi.Framework.Net6/Yi.Framework.Common/IOCOptions/JWTTokenOptions.cs b/Yi.Framework.Net6/Yi.Framework.Common/IOCOptions/JWTTokenOptions.cs index 89fd0993..9403d337 100644 --- a/Yi.Framework.Net6/Yi.Framework.Common/IOCOptions/JWTTokenOptions.cs +++ b/Yi.Framework.Net6/Yi.Framework.Common/IOCOptions/JWTTokenOptions.cs @@ -1,32 +1,21 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Text; using System.Threading.Tasks; namespace Yi.Framework.Common.IOCOptions { public class JWTTokenOptions { - public string Audience - { - get; - set; - } - public string SecurityKey - { - get; - set; - } - //public SigningCredentials Credentials - //{ - // get; - // set; - //} - public string Issuer - { - get; - set; - } + public string Audience { get; set; } + + public string Issuer { get; set; } + + public string SecurityKey { get; set; } + + public string DefaultScheme { get; set; } + public int Expiration { get; set; } + + public int ReExpiration { get; set; } } } diff --git a/Yi.Framework.Net6/Yi.Framework.Common/Models/Enum/ResultCode.cs b/Yi.Framework.Net6/Yi.Framework.Common/Models/Enum/ResultCode.cs new file mode 100644 index 00000000..3e049148 --- /dev/null +++ b/Yi.Framework.Net6/Yi.Framework.Common/Models/Enum/ResultCode.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Yi.Framework.Common.Models.Enum +{ + public enum ResultCode + { + /// + /// 操作成功。 + /// + Success = 200, + + /// + /// 操作不成功 + /// + NotSuccess = 500, + + /// + /// 无权限 + /// + NoPermission = 401, + + /// + /// Access过期 + /// + AccessTokenExpire = 1001, + + /// + /// Refresh过期 + /// + RefreshTokenExpire = 1002, + + /// + /// 没有角色登录 + /// + NoRoleLogin = 1003, + } +} diff --git a/Yi.Framework.Net6/Yi.Framework.Common/Models/Result.cs b/Yi.Framework.Net6/Yi.Framework.Common/Models/Result.cs index 890b01f7..3e2e1cac 100644 --- a/Yi.Framework.Net6/Yi.Framework.Common/Models/Result.cs +++ b/Yi.Framework.Net6/Yi.Framework.Common/Models/Result.cs @@ -1,70 +1,90 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; +using Microsoft.Extensions.Localization; +using Yi.Framework.Common.Models.Enum; +using Yi.Framework.Language; namespace Yi.Framework.Common.Models { - /// - /// 结果数据 - /// public class Result { + public static IStringLocalizer _local; + public ResultCode code { get; set; } + public bool status { get; set; } - public int code { get; set; } - public string msg { get; set; } + public string message { get; set; } public object data { get; set; } - public static Result Instance(bool status, string msg) + public static Result Expire(ResultCode code, string msg="") { - return new Result() { status = status, code = 500, msg = msg }; + return new Result() { code = code, status=false, message = Get(msg, "token_expiration") }; } - public static Result Error(string msg = "fail") + public static Result Error(string msg = "") { - return new Result() { status = false, code = 500, msg = msg }; + return new Result() { code = ResultCode.NotSuccess,status=false, message =Get(msg, "fail") }; } - public static Result Success(string msg = "succeed") + public static Result Success(string msg = "") { - return new Result() { status = true, code = 200, msg = msg }; + return new Result() { code = ResultCode.Success,status=true, message =Get( msg, "succeed" )}; } - public static Result UnAuthorize(string msg = "unAuthorize") + public static Result SuccessError(string msg = "") { - return new Result() { status = false, code = 401, msg = msg }; + return new Result() { code = ResultCode.Success, status = false, message = Get(msg, "fail") }; } + + public static Result UnAuthorize(string msg = "") + { + return new Result() { code = ResultCode.NoPermission,status=false, message = Get(msg, "unAuthorize") }; + } + public Result SetStatus(bool _status) + { + this.status = _status; + return this; + } public Result SetData(object obj) { this.data = obj; return this; } - public Result SetCode(int Code) + public Result SetCode(ResultCode Code) { this.code = Code; return this; } + public Result StatusFalse() + { + this.status = false; + return this; + } + public Result StatusTrue() + { + this.status = true; + return this; + } + + public static string Get(string msg,string msg2) + { + if (msg=="") + { + msg = _local[msg2]; + } + return msg; + } } public class Result { - public bool status { get; set; } - public int code { get; set; } - public string msg { get; set; } + public ResultCode code { get; set; } + public string message { get; set; } public T data { get; set; } - - public static Result Instance(bool status, string msg) - { - return new Result() { status = status, code = 500, msg = msg }; - } public static Result Error(string msg = "fail") { - return new Result { status = false, code = 500, msg = msg }; + return new Result() { code = ResultCode.NotSuccess, message = msg }; } public static Result Success(string msg = "succeed") { - return new Result { status = true, code = 200, msg = msg }; + return new Result() { code = ResultCode.Success, message = msg }; } - public static Result UnAuthorize(string msg = "unAuthorize") { - return new Result{ status = false, code = 401, msg = msg }; + return new Result() { code = ResultCode.NoPermission, message = msg }; } public Result SetData(T TValue) @@ -72,6 +92,11 @@ namespace Yi.Framework.Common.Models this.data = TValue; return this; } - } + public Result SetCode(ResultCode Code) + { + this.code = Code; + return this; + } + } } \ No newline at end of file diff --git a/Yi.Framework.Net6/Yi.Framework.Common/Models/ServiceLocator.cs b/Yi.Framework.Net6/Yi.Framework.Common/Models/ServiceLocator.cs new file mode 100644 index 00000000..09b6c5cd --- /dev/null +++ b/Yi.Framework.Net6/Yi.Framework.Common/Models/ServiceLocator.cs @@ -0,0 +1,10 @@ +using System; + +namespace Yi.Framework.Common.Models +{ + public static class ServiceLocator + { + public static IServiceProvider Instance { get; set; } + } + +} diff --git a/Yi.Framework.Net6/Yi.Framework.Common/Yi.Framework.Common.csproj b/Yi.Framework.Net6/Yi.Framework.Common/Yi.Framework.Common.csproj index bea37057..70af49f1 100644 --- a/Yi.Framework.Net6/Yi.Framework.Common/Yi.Framework.Common.csproj +++ b/Yi.Framework.Net6/Yi.Framework.Common/Yi.Framework.Common.csproj @@ -6,7 +6,12 @@ + + + + + diff --git a/Yi.Framework.Net6/Yi.Framework.Core/CacheClientDB.cs b/Yi.Framework.Net6/Yi.Framework.Core/CacheClientDB.cs index c9ffbb7e..a5b6c3a3 100644 --- a/Yi.Framework.Net6/Yi.Framework.Core/CacheClientDB.cs +++ b/Yi.Framework.Net6/Yi.Framework.Core/CacheClientDB.cs @@ -1,8 +1,4 @@ using Microsoft.Extensions.Options; -using ServiceStack; -using ServiceStack.Redis; -using ServiceStack.Redis.Pipeline; -using ServiceStack.Text; using System; using System.Collections; using System.Collections.Generic; @@ -12,1068 +8,78 @@ using System.Text; using System.Threading.Tasks; using System.IO; using Yi.Framework.Common.IOCOptions; +using CSRedis; namespace Yi.Framework.Core { - public class CacheClientDB : IDisposable - { - private readonly RedisConnOptions _RedisOptions; - - #region TestRedisCrack - //static CacheClientDB() - //{ - // try - // { - // Parallel.For(0, 10000, (i) => - // { - // using (RedisClient client = new RedisClient("192.168.3.254")) - // { - // client.Set("name" + i, i); - // client.Incr("name" + i); - // Console.WriteLine(i); - // } - - // }); - // Console.WriteLine("ok"); - - // Console.WriteLine("Hello World!"); - // } - // catch (Exception ex) - // { - // Console.WriteLine(ex.Message); - // } - //} - #endregion - public CacheClientDB(IOptionsMonitor redisConnOptions) - { - this._RedisOptions = redisConnOptions.CurrentValue; - client = new RedisClient(_RedisOptions.Host, _RedisOptions.Prot, _RedisOptions.Password, _RedisOptions.DB); - } - // 管道模式 三种模式 - public IRedisClient GetClient() - { - return client; - } - private IRedisClient client; - - public void Dispose() - { - - this.TryCatchException(delegate - { - this.client.Dispose(); - }, string.Empty); - } - // 为了以后全链路做准备 - private void TryCatchException(Action action, string key) - { - try - { - action(); - } - catch (Exception e) - { - - Console.WriteLine(e.Message); - } - } - - private T TryCatch(Func action, string key) - { - Stopwatch sw = Stopwatch.StartNew(); - //Exception ex = null; - //bool isError = false; - T result; - try - { - result = action(); - } - catch (Exception exinfo) - { - object p=null; - result =(T)p; - //isError = true; - Console.WriteLine(exinfo); - - } - finally - { - - sw.Stop(); - - } - - return result; - } - - private void TryCatch(Action action, string key) - { - - Stopwatch sw = Stopwatch.StartNew(); - //bool isError = false; - //Exception ex = null; - try - { - action(); - } - catch (Exception exinfo) - { - - //isError = true; - Console.WriteLine(exinfo); - } - finally - { - sw.Stop(); - - } - } - public bool Add(string key, T value) - { - - return this.TryCatch(() => this.client.Add(key, value), key); - } - /// - /// 简单模式 事务模式 - /// - /// - /// - /// - /// - /// - public bool Add(string key, T value, DateTime expiresAt) - { - - return this.TryCatch(() => this.client.Add(key, value, expiresAt), key); - } - - public bool Add(string key, T value, TimeSpan expiresIn) - { - return this.TryCatch(() => this.client.Add(key, value, expiresIn), key); - } - - public long Decrement(string key, uint amount) - { - return this.TryCatch(() => this.client.Decrement(key, amount), key); - } - - public void FlushAll() - { - this.TryCatch(delegate - { - this.client.FlushAll(); - }, string.Empty); - } - - public T Get(string key) - { - return this.TryCatch(() => this.client.Get(key), key); - } - - public IDictionary GetAll(IEnumerable keys) - { - return this.TryCatch>(() => this.client.GetAll(keys), keys.FirstOrDefault()); - } - - public long Increment(string key, uint amount) - { - return this.TryCatch(() => this.client.Increment(key, amount), key); - } - - public bool Remove(string key) - { - return this.TryCatch(() => this.client.Remove(key), key); - } - - public void RemoveAll(IEnumerable keys) - { - this.TryCatch(delegate - { - this.client.RemoveAll(keys); - }, keys.FirstOrDefault()); - } - - public bool Replace(string key, T value) - { - return this.TryCatch(() => this.client.Replace(key, value), key); - } - - public bool Replace(string key, T value, DateTime expiresAt) - { - return this.TryCatch(() => this.client.Replace(key, value, expiresAt), key); - } - - public bool Replace(string key, T value, TimeSpan expiresIn) - { - return this.TryCatch(() => this.client.Replace(key, value, expiresIn), key); - } - - public bool Set(string key, T value) - { - return this.TryCatch(() => this.client.Set(key, value), key); - } - - public bool Set(string key, T value, DateTime expiresAt) - { - return this.TryCatch(() => this.client.Set(key, value, expiresAt), key); - } - - public bool Set(string key, T value, TimeSpan expiresIn) - { - return this.TryCatch(() => this.client.Set(key, value, expiresIn), key); - } - - public void SetAll(IDictionary values) - { - this.TryCatch(delegate - { - this.client.SetAll(values); - }, values.Keys.FirstOrDefault()); - } - - - public void Delete(T entity) where T : class, new() - { - this.TryCatch(delegate - { - this.client.Delete(entity); - }, string.Empty); - } - - public void DeleteAll() where TEntity : class, new() - { - this.TryCatch(delegate - { - this.client.DeleteAll(); - }, string.Empty); - } - - public void DeleteById(object id) where T : class, new() - { - this.TryCatch(delegate - { - this.client.DeleteById(id); - }, string.Empty); - } - - public void DeleteByIds(ICollection ids) where T : class, new() - { - this.TryCatch(delegate - { - this.client.DeleteById(ids); - }, string.Empty); - } - - public T GetById(object id) where T : class, new() - { - return this.TryCatch(() => this.client.GetById(id), string.Empty); - } - - public IList GetByIds(ICollection ids) where T : class, new() - { - return this.TryCatch>(() => this.client.GetByIds(ids), string.Empty); - } - - public T Store(T entity) where T : class, new() - { - return this.TryCatch(() => this.client.Store(entity), string.Empty); - } - - public void StoreAll(IEnumerable entities) where TEntity : class, new() - { - this.TryCatch(delegate - { - this.client.StoreAll(entities); - }, string.Empty); - } - - public void AddItemToList(string listId, string value) - { - this.TryCatch(delegate - { - this.client.AddItemToList(listId, value); - }, listId); - } - - public void AddItemToSet(string setId, string item) - { - this.TryCatch(delegate - { - this.client.AddItemToSet(setId, item); - }, setId); - } - - public bool AddItemToSortedSet(string setId, string value) - { - return this.TryCatch(() => this.client.AddItemToSortedSet(setId, value), setId); - } - - public bool AddItemToSortedSet(string setId, string value, double score) - { - return this.TryCatch(() => this.client.AddItemToSortedSet(setId, value, score), setId); - } - - public void AddRangeToList(string listId, List values) - { - this.TryCatch(delegate - { - this.client.AddRangeToList(listId, values); - }, listId); - } - - public void AddRangeToSet(string setId, List items) - { - this.TryCatch(delegate - { - this.client.AddRangeToSet(setId, items); - }, setId); - } - - public bool AddRangeToSortedSet(string setId, List values, double score) - { - return this.TryCatch(() => this.client.AddRangeToSortedSet(setId, values, score), setId); - } - - public bool AddRangeToSortedSet(string setId, List values, long score) - { - return this.TryCatch(() => this.client.AddRangeToSortedSet(setId, values, score), setId); - } - - public long AppendToValue(string key, string value) - { - return this.TryCatch(() => this.client.AppendToValue(key, value), key); - } - - public string BlockingDequeueItemFromList(string listId, TimeSpan? timeOut) - { - return this.TryCatch(() => this.client.BlockingDequeueItemFromList(listId, timeOut), listId); - } - - public KeyValuePair BlockingDequeueItemFromLists(string[] listIds, TimeSpan? timeOut) - { - return this.TryCatch>(delegate - { - ItemRef item = this.client.BlockingDequeueItemFromLists(listIds, timeOut); - return new KeyValuePair(item.Id, item.Item); - }, listIds[0]); - } - - public string BlockingPopAndPushItemBetweenLists(string fromListId, string toListId, TimeSpan? timeOut) - { - return this.TryCatch(() => this.client.BlockingPopAndPushItemBetweenLists(fromListId, toListId, timeOut), fromListId); - } - - public string BlockingPopItemFromList(string listId, TimeSpan? timeOut) - { - return this.TryCatch(() => this.client.BlockingPopItemFromList(listId, timeOut), listId); - } - - public KeyValuePair BlockingPopItemFromLists(string[] listIds, TimeSpan? timeOut) - { - return this.TryCatch>(delegate - { - ItemRef item = this.client.BlockingPopItemFromLists(listIds, timeOut); - return new KeyValuePair(item.Id, item.Item); - }, listIds[0]); - } - - public string BlockingRemoveStartFromList(string listId, TimeSpan? timeOut) - { - return this.TryCatch(() => this.client.BlockingRemoveStartFromList(listId, timeOut), listId); - } - - public KeyValuePair BlockingRemoveStartFromLists(string[] listIds, TimeSpan? timeOut) - { - return this.TryCatch>(delegate - { - ItemRef item = this.client.BlockingRemoveStartFromLists(listIds, timeOut); - return new KeyValuePair(item.Id, item.Item); - }, listIds[0]); - } - - public bool ContainsKey(string key) - { - return this.TryCatch(() => this.client.ContainsKey(key), key); - } - - public long DecrementValue(string key) - { - return this.TryCatch(() => this.client.DecrementValue(key), key); - } - - public long DecrementValueBy(string key, int count) - { - return this.TryCatch(() => this.client.DecrementValueBy(key, count), key); - } - - public string DequeueItemFromList(string listId) - { - return this.TryCatch(() => this.client.DequeueItemFromList(listId), listId); - } - - public void EnqueueItemOnList(string listId, string value) - { - this.TryCatch(delegate - { - this.client.EnqueueItemOnList(listId, value); - }, listId); - } - - public bool ExpireEntryAt(string key, DateTime expireAt) - { - return this.TryCatch(() => this.client.ExpireEntryAt(key, expireAt), key); - } - - public bool ExpireEntryIn(string key, TimeSpan expireIn) - { - return this.TryCatch(() => this.client.ExpireEntryIn(key, expireIn), key); - } - - public Dictionary GetAllEntriesFromHash(string hashId) - { - return this.TryCatch>(() => this.client.GetAllEntriesFromHash(hashId), hashId); - } - - public List GetAllItemsFromList(string listId) - { - return this.TryCatch>(() => this.client.GetAllItemsFromList(listId), listId); - } - - public HashSet GetAllItemsFromSet(string setId) - { - return this.TryCatch>(() => this.client.GetAllItemsFromSet(setId), setId); - } - - public List GetAllItemsFromSortedSet(string setId) - { - return this.TryCatch>(() => this.client.GetAllItemsFromSortedSet(setId), setId); - } - - public List GetAllItemsFromSortedSetDesc(string setId) - { - return this.TryCatch>(() => this.client.GetAllItemsFromSortedSetDesc(setId), setId); - } - - public List GetAllKeys() - { - return this.TryCatch>(() => this.client.GetAllKeys(), string.Empty); - } - - public IDictionary GetAllWithScoresFromSortedSet(string setId) - { - return this.TryCatch>(() => this.client.GetAllWithScoresFromSortedSet(setId), setId); - } - - public string GetAndSetEntry(string key, string value) - { - return this.TryCatch(() => this.client.GetAndSetValue(key, value), key); - } - - public HashSet GetDifferencesFromSet(string fromSetId, params string[] withSetIds) - { - return this.TryCatch>(() => this.client.GetDifferencesFromSet(fromSetId, withSetIds), fromSetId); - } - - public T GetFromHash(object id) - { - return this.TryCatch(() => this.client.GetFromHash(id), string.Empty); - } - - public long GetHashCount(string hashId) - { - return this.TryCatch(() => this.client.GetHashCount(hashId), hashId); - } - - public List GetHashKeys(string hashId) - { - return this.TryCatch>(() => this.client.GetHashKeys(hashId), hashId); - } - - public List GetHashValues(string hashId) - { - return this.TryCatch>(() => this.client.GetHashValues(hashId), hashId); - } - - public HashSet GetIntersectFromSets(params string[] setIds) - { - return this.TryCatch>(() => this.client.GetIntersectFromSets(setIds), setIds[0]); - } - - public string GetItemFromList(string listId, int listIndex) - { - return this.TryCatch(() => this.client.GetItemFromList(listId, listIndex), listId); - } - - public long GetItemIndexInSortedSet(string setId, string value) - { - return this.TryCatch(() => this.client.GetItemIndexInSortedSet(setId, value), setId); - } - - public long GetItemIndexInSortedSetDesc(string setId, string value) - { - return this.TryCatch(() => this.client.GetItemIndexInSortedSetDesc(setId, value), setId); - } - - public double GetItemScoreInSortedSet(string setId, string value) - { - return this.TryCatch(() => this.client.GetItemScoreInSortedSet(setId, value), setId); - } - - public long GetListCount(string listId) - { - return this.TryCatch(() => this.client.GetListCount(listId), listId); - } - - public string GetRandomItemFromSet(string setId) - { - return this.TryCatch(() => this.client.GetRandomItemFromSet(setId), setId); - } - - public List GetRangeFromList(string listId, int startingFrom, int endingAt) - { - return this.TryCatch>(() => this.client.GetRangeFromList(listId, startingFrom, endingAt), listId); - } - - public List GetRangeFromSortedList(string listId, int startingFrom, int endingAt) - { - return this.TryCatch>(() => this.client.GetRangeFromSortedList(listId, startingFrom, endingAt), listId); - } - - public List GetRangeFromSortedSet(string setId, int fromRank, int toRank) - { - return this.TryCatch>(() => this.client.GetRangeFromSortedSet(setId, fromRank, toRank), setId); - } - - public List GetRangeFromSortedSetByHighestScore(string setId, double fromScore, double toScore) - { - return this.TryCatch>(() => this.client.GetRangeFromSortedSetByHighestScore(setId, fromScore, toScore), setId); - } - - public List GetRangeFromSortedSetByHighestScore(string setId, long fromScore, long toScore) - { - return this.TryCatch>(() => this.client.GetRangeFromSortedSetByHighestScore(setId, fromScore, toScore), setId); - } - - public List GetRangeFromSortedSetByHighestScore(string setId, string fromStringScore, string toStringScore) - { - return this.TryCatch>(() => this.client.GetRangeFromSortedSetByHighestScore(setId, fromStringScore, toStringScore), setId); - } - - public List GetRangeFromSortedSetByHighestScore(string setId, double fromScore, double toScore, int? skip, int? take) - { - return this.TryCatch>(() => this.client.GetRangeFromSortedSetByHighestScore(setId, fromScore, toScore, skip, take), setId); - } - - public List GetRangeFromSortedSetByHighestScore(string setId, long fromScore, long toScore, int? skip, int? take) - { - return this.TryCatch>(() => this.client.GetRangeFromSortedSetByHighestScore(setId, fromScore, toScore, skip, take), setId); - } - - public List GetRangeFromSortedSetByHighestScore(string setId, string fromStringScore, string toStringScore, int? skip, int? take) - { - return this.TryCatch>(() => this.client.GetRangeFromSortedSetByHighestScore(setId, fromStringScore, toStringScore, skip, take), setId); - } - - public List GetRangeFromSortedSetByLowestScore(string setId, double fromScore, double toScore) - { - return this.TryCatch>(() => this.client.GetRangeFromSortedSetByLowestScore(setId, fromScore, toScore), setId); - } - - public List GetRangeFromSortedSetByLowestScore(string setId, long fromScore, long toScore) - { - return this.TryCatch>(() => this.client.GetRangeFromSortedSetByLowestScore(setId, fromScore, toScore), setId); - } - - public List GetRangeFromSortedSetByLowestScore(string setId, string fromStringScore, string toStringScore) - { - return this.TryCatch>(() => this.client.GetRangeFromSortedSetByLowestScore(setId, fromStringScore, toStringScore), setId); - } - - public List GetRangeFromSortedSetByLowestScore(string setId, double fromScore, double toScore, int? skip, int? take) - { - return this.TryCatch>(() => this.client.GetRangeFromSortedSetByLowestScore(setId, fromScore, toScore, skip, take), setId); - } - - public List GetRangeFromSortedSetByLowestScore(string setId, long fromScore, long toScore, int? skip, int? take) - { - return this.TryCatch>(() => this.client.GetRangeFromSortedSetByLowestScore(setId, fromScore, toScore, skip, take), setId); - } - - public List GetRangeFromSortedSetByLowestScore(string setId, string fromStringScore, string toStringScore, int? skip, int? take) - { - return this.TryCatch>(() => this.client.GetRangeFromSortedSetByLowestScore(setId, fromStringScore, toStringScore, skip, take), setId); - } - - public List GetRangeFromSortedSetDesc(string setId, int fromRank, int toRank) - { - return this.TryCatch>(() => this.client.GetRangeFromSortedSetDesc(setId, fromRank, toRank), setId); - } - - public IDictionary GetRangeWithScoresFromSortedSet(string setId, int fromRank, int toRank) - { - return this.TryCatch>(() => this.client.GetRangeWithScoresFromSortedSet(setId, fromRank, toRank), setId); - } - - public IDictionary GetRangeWithScoresFromSortedSetByHighestScore(string setId, double fromScore, double toScore) - { - return this.TryCatch>(() => this.client.GetRangeWithScoresFromSortedSetByHighestScore(setId, fromScore, toScore), setId); - } - - public IDictionary GetRangeWithScoresFromSortedSetByHighestScore(string setId, long fromScore, long toScore) - { - return this.TryCatch>(() => this.client.GetRangeWithScoresFromSortedSetByHighestScore(setId, fromScore, toScore), setId); - } - - public IDictionary GetRangeWithScoresFromSortedSetByHighestScore(string setId, string fromStringScore, string toStringScore) - { - return this.TryCatch>(() => this.client.GetRangeWithScoresFromSortedSetByHighestScore(setId, fromStringScore, toStringScore), setId); - } - - public IDictionary GetRangeWithScoresFromSortedSetByHighestScore(string setId, double fromScore, double toScore, int? skip, int? take) - { - return this.TryCatch>(() => this.client.GetRangeWithScoresFromSortedSetByHighestScore(setId, fromScore, toScore, skip, take), setId); - } - - public IDictionary GetRangeWithScoresFromSortedSetByHighestScore(string setId, long fromScore, long toScore, int? skip, int? take) - { - return this.TryCatch>(() => this.client.GetRangeWithScoresFromSortedSetByHighestScore(setId, fromScore, toScore, skip, take), setId); - } - - public IDictionary GetRangeWithScoresFromSortedSetByHighestScore(string setId, string fromStringScore, string toStringScore, int? skip, int? take) - { - return this.TryCatch>(() => this.client.GetRangeWithScoresFromSortedSetByHighestScore(setId, fromStringScore, toStringScore, skip, take), setId); - } - - public IDictionary GetRangeWithScoresFromSortedSetByLowestScore(string setId, double fromScore, double toScore) - { - return this.TryCatch>(() => this.client.GetRangeWithScoresFromSortedSetByHighestScore(setId, fromScore, toScore), setId); - } - - public IDictionary GetRangeWithScoresFromSortedSetByLowestScore(string setId, long fromScore, long toScore) - { - return this.TryCatch>(() => this.client.GetRangeWithScoresFromSortedSetByLowestScore(setId, fromScore, toScore), setId); - } - - public IDictionary GetRangeWithScoresFromSortedSetByLowestScore(string setId, string fromStringScore, string toStringScore) - { - return this.TryCatch>(() => this.client.GetRangeWithScoresFromSortedSetByLowestScore(setId, fromStringScore, toStringScore), setId); - } - - public IDictionary GetRangeWithScoresFromSortedSetByLowestScore(string setId, double fromScore, double toScore, int? skip, int? take) - { - return this.TryCatch>(() => this.client.GetRangeWithScoresFromSortedSetByLowestScore(setId, fromScore, toScore, skip, take), setId); - } - - public IDictionary GetRangeWithScoresFromSortedSetByLowestScore(string setId, long fromScore, long toScore, int? skip, int? take) - { - return this.TryCatch>(() => this.client.GetRangeWithScoresFromSortedSetByLowestScore(setId, fromScore, toScore, skip, take), setId); - } - - public IDictionary GetRangeWithScoresFromSortedSetByLowestScore(string setId, string fromStringScore, string toStringScore, int? skip, int? take) - { - return this.TryCatch>(() => this.client.GetRangeWithScoresFromSortedSetByLowestScore(setId, fromStringScore, toStringScore, skip, take), setId); - } - - public IDictionary GetRangeWithScoresFromSortedSetDesc(string setId, int fromRank, int toRank) - { - return this.TryCatch>(() => this.client.GetRangeWithScoresFromSortedSetDesc(setId, fromRank, toRank), setId); - } - - public long GetSetCount(string setId) - { - return this.TryCatch(() => this.client.GetSetCount(setId), setId); - } - - public List GetSortedEntryValues(string key, int startingFrom, int endingAt) - { - return this.TryCatch>(() => this.client.GetSortedEntryValues(key, startingFrom, endingAt), key); - } - - public long GetSortedSetCount(string setId) - { - return this.TryCatch(() => this.client.GetSortedSetCount(setId), setId); - } - - public long GetSortedSetCount(string setId, double fromScore, double toScore) - { - return this.TryCatch(() => this.client.GetSortedSetCount(setId, fromScore, toScore), setId); - } - - public long GetSortedSetCount(string setId, long fromScore, long toScore) - { - return this.TryCatch(() => this.client.GetSortedSetCount(setId, fromScore, toScore), setId); - } - - public long GetSortedSetCount(string setId, string fromStringScore, string toStringScore) - { - return this.TryCatch(() => this.client.GetSortedSetCount(setId, fromStringScore, toStringScore), setId); - } - - public string GetSubstring(string key, int fromIndex, int toIndex) - { - return this.TryCatch(delegate - { - byte[] bytes = ((RedisClient)this.client).GetRange(key, fromIndex, toIndex); - if (bytes != null) - { - return StringExtensions.FromUtf8Bytes(bytes); - } - return null; - }, key); - } - - public TimeSpan GetTimeToLive(string key) - { - return this.TryCatch(delegate - { - TimeSpan? t = this.client.GetTimeToLive(key); - if (!t.HasValue) - { - return TimeSpan.Zero; - } - return t.Value; - }, key); - } - - public HashSet GetUnionFromSets(params string[] setIds) - { - return this.TryCatch>(() => this.client.GetUnionFromSets(setIds), setIds[0]); - } - - public string GetValue(string key) - { - return this.TryCatch(() => this.client.GetValue(key), key); - } - - public string GetValueFromHash(string hashId, string key) - { - return this.TryCatch(() => this.client.GetValueFromHash(hashId, key), hashId); - } - - public List GetValues(List keys) - { - return this.TryCatch>(() => this.client.GetValues(keys), keys[0]); - } - - public List GetValues(List keys) - { - return this.TryCatch>(() => this.client.GetValues(keys), keys[0]); - } - - public List GetValuesFromHash(string hashId, params string[] keys) - { - return this.TryCatch>(() => this.client.GetValuesFromHash(hashId, keys), hashId); - } - - public Dictionary GetValuesMap(List keys) - { - return this.TryCatch>(() => this.client.GetValuesMap(keys), keys[0]); - } - - public Dictionary GetValuesMap(List keys) - { - return this.TryCatch>(() => this.client.GetValuesMap(keys), keys[0]); - } - - public bool HashContainsEntry(string hashId, string key) - { - return this.TryCatch(() => this.client.HashContainsEntry(hashId, key), hashId); - } - - public double IncrementItemInSortedSet(string setId, string value, double incrementBy) - { - return this.TryCatch(() => this.client.IncrementItemInSortedSet(setId, value, incrementBy), setId); - } - - public double IncrementItemInSortedSet(string setId, string value, long incrementBy) - { - return this.TryCatch(() => this.client.IncrementItemInSortedSet(setId, value, incrementBy), setId); - } - - public long IncrementValue(string key) - { - return this.TryCatch(() => this.client.IncrementValue(key), key); - } - - public long IncrementValueBy(string key, int count) - { - return this.TryCatch(() => this.client.IncrementValueBy(key, count), key); - } - - public long IncrementValueInHash(string hashId, string key, int incrementBy) - { - return this.TryCatch(() => this.client.IncrementValueInHash(hashId, key, incrementBy), hashId); - } - - public void MoveBetweenSets(string fromSetId, string toSetId, string item) - { - this.TryCatch(delegate - { - this.client.MoveBetweenSets(fromSetId, toSetId, item); - }, fromSetId); - } - - public string PopAndPushItemBetweenLists(string fromListId, string toListId) - { - return this.TryCatch(() => this.client.PopAndPushItemBetweenLists(fromListId, toListId), fromListId); - } - - public string PopItemFromList(string listId) - { - return this.TryCatch(() => this.client.PopItemFromList(listId), listId); - } - - public string PopItemFromSet(string setId) - { - return this.TryCatch(() => this.client.PopItemFromSet(setId), setId); - } - - public string PopItemWithHighestScoreFromSortedSet(string setId) - { - return this.TryCatch(() => this.client.PopItemWithHighestScoreFromSortedSet(setId), setId); - } - - public string PopItemWithLowestScoreFromSortedSet(string setId) - { - return this.TryCatch(() => this.client.PopItemWithLowestScoreFromSortedSet(setId), setId); - } - - public void PrependItemToList(string listId, string value) - { - this.TryCatch(delegate - { - this.client.PrependItemToList(listId, value); - }, listId); - } - - public void PrependRangeToList(string listId, List values) - { - this.TryCatch(delegate - { - this.client.PrependRangeToList(listId, values); - }, listId); - } - - public long PublishMessage(string toChannel, string message) - { - return this.TryCatch(() => this.client.PublishMessage(toChannel, message), string.Empty); - } - - public void PushItemToList(string listId, string value) - { - this.TryCatch(delegate - { - this.client.PushItemToList(listId, value); - }, listId); - } - - public void RemoveAllFromList(string listId) - { - this.TryCatch(delegate - { - this.client.Remove(listId); - }, listId); - } - - public string RemoveEndFromList(string listId) - { - return this.TryCatch(() => this.client.RemoveEndFromList(listId), listId); - } - - public bool RemoveEntry(params string[] args) - { - return this.TryCatch(() => this.client.RemoveEntry(args), args[0]); - } - - public bool RemoveEntryFromHash(string hashId, string key) - { - return this.TryCatch(() => this.client.RemoveEntryFromHash(hashId, key), hashId); - } - - public long RemoveItemFromList(string listId, string value) - { - return this.TryCatch(() => this.client.RemoveItemFromList(listId, value), listId); - } - - public long RemoveItemFromList(string listId, string value, int noOfMatches) - { - return this.TryCatch(() => this.client.RemoveItemFromList(listId, value, noOfMatches), listId); - } - - public void RemoveItemFromSet(string setId, string item) - { - this.TryCatch(delegate - { - this.client.RemoveItemFromSet(setId, item); - }, setId); - } - - public bool RemoveItemFromSortedSet(string setId, string value) - { - return this.TryCatch(() => this.client.RemoveItemFromSortedSet(setId, value), setId); - } - /// - /// 骚操作-- redis 连接池-- 如果出现高并发,客户端的连接数量会上限,为了节省资源,重复利用连接对象,通过线程池去获取连接 - /// - /// - /// - /// - /// - public static IRedisClientsManager GetPoolClient(string host, int port, int db) - { - return new PooledRedisClientManager(db, host + ":" + port); - } - public long RemoveRangeFromSortedSet(string setId, int minRank, int maxRank) - { - return this.TryCatch(() => this.client.RemoveRangeFromSortedSet(setId, minRank, maxRank), setId); - } - - public long RemoveRangeFromSortedSetByScore(string setId, double fromScore, double toScore) - { - return this.TryCatch(() => this.client.RemoveRangeFromSortedSetByScore(setId, fromScore, toScore), setId); - } - - public long RemoveRangeFromSortedSetByScore(string setId, long fromScore, long toScore) - { - return this.TryCatch(() => this.client.RemoveRangeFromSortedSetByScore(setId, fromScore, toScore), setId); - } - - public string RemoveStartFromList(string listId) - { - return this.TryCatch(() => this.client.RemoveStartFromList(listId), listId); - } - - public void RenameKey(string fromName, string toName) - { - this.TryCatch(delegate - { - this.client.RenameKey(fromName, toName); - }, string.Empty); - } - - public List SearchKeys(string pattern) - { - return this.TryCatch>(() => this.client.SearchKeys(pattern), pattern); - } - - public void SetAll(Dictionary map) - { - this.TryCatch(delegate - { - this.client.SetAll(map); - }, string.Empty); - } - - public void SetAll(IEnumerable keys, IEnumerable values) - { - this.TryCatch(delegate - { - this.client.SetAll(keys, values); - }, string.Empty); - } - - public bool SetContainsItem(string setId, string item) - { - return this.TryCatch(() => this.client.SetContainsItem(setId, item), setId); - } - - public void SetEntry(string key, string value) - { - this.TryCatch(delegate - { - this.client.SetValue(key, value); - }, key); - } - - public void SetEntry(string key, string value, TimeSpan expireIn) - { - this.TryCatch(delegate - { - this.client.SetValue(key, value, expireIn); - }, key); - } - - public bool SetEntryIfNotExists(string key, string value) - { - return this.TryCatch(() => this.client.SetValueIfNotExists(key, value), key); - } - - public bool SetEntryInHash(string hashId, string key, string value) - { - return this.TryCatch(() => this.client.SetEntryInHash(hashId, key, value), hashId); - } - - public bool SetEntryInHashIfNotExists(string hashId, string key, string value) - { - return this.TryCatch(() => this.client.SetEntryInHashIfNotExists(hashId, key, value), hashId); - } - - public void SetItemInList(string listId, int listIndex, string value) - { - this.TryCatch(delegate - { - this.client.SetItemInList(listId, listIndex, value); - }, listId); - } - - public void SetRangeInHash(string hashId, IEnumerable> keyValuePairs) - { - this.TryCatch(delegate - { - this.client.SetRangeInHash(hashId, keyValuePairs); - }, hashId); - } - - public bool SortedSetContainsItem(string setId, string value) - { - return this.TryCatch(() => this.client.SortedSetContainsItem(setId, value), setId); - } - - public void StoreAsHash(T entity) - { - this.TryCatch(delegate - { - this.client.StoreAsHash(entity); - }, string.Empty); - } - - - public bool SetEntryInHash(string hashId, string key, T value) - { - - return this.TryCatch(() => this.client.SetEntryInHash(hashId, key, TextExtensions.SerializeToString(value)), hashId); - } - public bool SetEntryInHash(string hashId, string key, T value, TimeSpan expiresIn) - { - - return this.TryCatch(() => this.client.SetEntryInHash(hashId, key, TextExtensions.SerializeToString(value)), hashId); - } - public T GetValueFromHash(string hashId, string key) - { - return this.TryCatch(() => JsonSerializer.DeserializeFromString(this.client.GetValueFromHash(hashId, key)), hashId); - } - - public bool SetEntryInHashIfNotExists(string hashId, string key, T value) - { - return this.TryCatch(() => this.client.SetEntryInHashIfNotExists(hashId, key, TextExtensions.SerializeToString(value)), hashId); - } - - public IDisposable AcquireLock(string key) - { - return this.TryCatch(() => this.client.AcquireLock(key), key); - } - - public IDisposable AcquireLock(string key, TimeSpan timeOut) - { - return this.TryCatch(() => this.client.AcquireLock(key, timeOut), key); - } - - - public DateTime GetServerTime() - { - return this.TryCatch(() => this.client.GetServerTime(), string.Empty); - } - - - } + public class CacheClientDB + { + + public delegate T MyAction(CSRedisClient client); + + private readonly RedisConnOptions _RedisOptions; + public CacheClientDB(IOptionsMonitor redisConnOptions) + { + this._RedisOptions = redisConnOptions.CurrentValue; + } + //public CSRedisClient GetClient() + //{ + // return client; + //} + //private CSRedisClient client=null; + + // 为了以后全链路做准备 + + private T TryCatch(MyAction action) + { + //Stopwatch sw = Stopwatch.StartNew(); + ////Exception ex = null; + ////bool isError = false; + var client2 = new CSRedisClient($"{_RedisOptions.Host}:{_RedisOptions.Prot},password={_RedisOptions.Password},defaultDatabase ={ _RedisOptions.DB }"); + T result; + try + { + result = action(client2); + } + catch (Exception exinfo) + { + object p = null; + result = (T)p; + //isError = true; + Console.WriteLine(exinfo); + + } + finally + { + client2.Dispose(); + } + + return result; + } + + + public bool Exit(string key) + { + return this.TryCatch((u) => u.Exists(key)); + } + + public long Remove(string key) + { + return this.TryCatch((u) => u.Del(key)); + } + + public T Get(string key) + { + return this.TryCatch((u) => u.Get(key)); + } + public bool Set(string key, T data, TimeSpan time) + { + return this.TryCatch((u) => u.Set(key, data, time)); + } + + public bool Set(string key, T data) + { + return this.TryCatch((u) => u.Set(key, data)); + } + } } diff --git a/Yi.Framework.Net6/Yi.Framework.Core/Library/Microsoft.Bcl.AsyncInterfaces.dll b/Yi.Framework.Net6/Yi.Framework.Core/Library/Microsoft.Bcl.AsyncInterfaces.dll deleted file mode 100644 index c695bdd5..00000000 Binary files a/Yi.Framework.Net6/Yi.Framework.Core/Library/Microsoft.Bcl.AsyncInterfaces.dll and /dev/null differ diff --git a/Yi.Framework.Net6/Yi.Framework.Core/Library/ServiceStack.Common.dll b/Yi.Framework.Net6/Yi.Framework.Core/Library/ServiceStack.Common.dll deleted file mode 100644 index f10b87b4..00000000 Binary files a/Yi.Framework.Net6/Yi.Framework.Core/Library/ServiceStack.Common.dll and /dev/null differ diff --git a/Yi.Framework.Net6/Yi.Framework.Core/Library/ServiceStack.Interfaces.dll b/Yi.Framework.Net6/Yi.Framework.Core/Library/ServiceStack.Interfaces.dll deleted file mode 100644 index 4dbba7ef..00000000 Binary files a/Yi.Framework.Net6/Yi.Framework.Core/Library/ServiceStack.Interfaces.dll and /dev/null differ diff --git a/Yi.Framework.Net6/Yi.Framework.Core/Library/ServiceStack.Redis.dll b/Yi.Framework.Net6/Yi.Framework.Core/Library/ServiceStack.Redis.dll deleted file mode 100644 index 5faefa26..00000000 Binary files a/Yi.Framework.Net6/Yi.Framework.Core/Library/ServiceStack.Redis.dll and /dev/null differ diff --git a/Yi.Framework.Net6/Yi.Framework.Core/Library/ServiceStack.Text.dll b/Yi.Framework.Net6/Yi.Framework.Core/Library/ServiceStack.Text.dll deleted file mode 100644 index 2f701811..00000000 Binary files a/Yi.Framework.Net6/Yi.Framework.Core/Library/ServiceStack.Text.dll and /dev/null differ diff --git a/Yi.Framework.Net6/Yi.Framework.Core/MakeJwt.cs b/Yi.Framework.Net6/Yi.Framework.Core/MakeJwt.cs index 08420c39..d38c64c8 100644 --- a/Yi.Framework.Net6/Yi.Framework.Core/MakeJwt.cs +++ b/Yi.Framework.Net6/Yi.Framework.Core/MakeJwt.cs @@ -14,10 +14,9 @@ using JwtRegisteredClaimNames = Microsoft.IdentityModel.JsonWebTokens.JwtRegiste namespace Yi.Framework.Core { - public class jwtUser + public class JwtUser { - public user user { get; set; } - public List menuIds { get; set; } + public User user { get; set; } } @@ -29,23 +28,23 @@ namespace Yi.Framework.Core /// /// /// - public static string app(jwtUser _user) + public static string app(JwtUser _user) { //通过查询权限,把所有权限加入进令牌中 List claims = new List(); claims.Add(new Claim(JwtRegisteredClaimNames.Nbf, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}")); claims.Add(new Claim(JwtRegisteredClaimNames.Exp, $"{new DateTimeOffset(DateTime.Now.AddMinutes(30)).ToUnixTimeSeconds()}")); - claims.Add(new Claim(ClaimTypes.Name, _user.user.username)); - claims.Add(new Claim(ClaimTypes.Sid, _user.user.id.ToString())); + claims.Add(new Claim(ClaimTypes.Name, _user.user.Username)); + claims.Add(new Claim(ClaimTypes.Sid, _user.user.Id.ToString())); //现在不存放在jwt中,而存放在redis中 //foreach (var k in _user?.menuIds) //{ // claims.Add(new Claim("menuIds",k.id.ToString())); //} - foreach (var k in _user.user.roles) - { - claims.Add(new Claim(ClaimTypes.Role, k.role_name)); - } + //foreach (var k in _user.user.roles) + //{ + // claims.Add(new Claim(ClaimTypes.Role, k.role_name)); + //} var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(JwtConst.SecurityKey)); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); diff --git a/Yi.Framework.Net6/Yi.Framework.Core/Yi.Framework.Core.csproj b/Yi.Framework.Net6/Yi.Framework.Core/Yi.Framework.Core.csproj index 220faf6d..a5773704 100644 --- a/Yi.Framework.Net6/Yi.Framework.Core/Yi.Framework.Core.csproj +++ b/Yi.Framework.Net6/Yi.Framework.Core/Yi.Framework.Core.csproj @@ -7,6 +7,7 @@ + @@ -40,4 +41,8 @@ + + + + diff --git a/Yi.Framework.Net6/Yi.Framework.DTOModel/ChangePwdDto.cs b/Yi.Framework.Net6/Yi.Framework.DTOModel/ChangePwdDto.cs deleted file mode 100644 index d8db8c1e..00000000 --- a/Yi.Framework.Net6/Yi.Framework.DTOModel/ChangePwdDto.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Yi.Framework.Model.Models; - -namespace Yi.Framework.DTOModel -{ - public class ChangePwdDto - { - public user user { get; set; } - public string newPassword { get; set; } - } -} diff --git a/Yi.Framework.Net6/Yi.Framework.DTOModel/ChildrenDto.cs b/Yi.Framework.Net6/Yi.Framework.DTOModel/ChildrenDto.cs deleted file mode 100644 index 18ee3742..00000000 --- a/Yi.Framework.Net6/Yi.Framework.DTOModel/ChildrenDto.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Yi.Framework.DTOModel -{ - public class ChildrenDto - { - public int parentId { get; set; } - public T data { get; set; } - } -} diff --git a/Yi.Framework.Net6/Yi.Framework.DTOModel/IdsDto.cs b/Yi.Framework.Net6/Yi.Framework.DTOModel/IdsDto.cs deleted file mode 100644 index 94a2ab1d..00000000 --- a/Yi.Framework.Net6/Yi.Framework.DTOModel/IdsDto.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace Yi.Framework.DTOModel -{ - public class IdDto - { - public T id1 { get; set; } - public T id2 { get; set; } - } - - public class IdsDto - { - public T id{ get; set; } - public List ids { get; set; } - } - - public class IdsListDto - { - public List ids1 { get; set; } - public List ids2 { get; set; } - } -} diff --git a/Yi.Framework.Net6/Yi.Framework.DTOModel/SettingDto.cs b/Yi.Framework.Net6/Yi.Framework.DTOModel/SettingDto.cs deleted file mode 100644 index 3e3dca70..00000000 --- a/Yi.Framework.Net6/Yi.Framework.DTOModel/SettingDto.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Yi.Framework.DTOModel -{ - public class SettingDto - { - public string InitIcon { get; set; } - public string InitRole { get; set; } - public string Title { get; set; } - public List ImageList { get; set; } - } -} diff --git a/Yi.Framework.Net6/Yi.Framework.DTOModel/Yi.Framework.DTOModel.csproj b/Yi.Framework.Net6/Yi.Framework.DTOModel/Yi.Framework.DTOModel.csproj index d0fe5f85..4e3e43b5 100644 --- a/Yi.Framework.Net6/Yi.Framework.DTOModel/Yi.Framework.DTOModel.csproj +++ b/Yi.Framework.Net6/Yi.Framework.DTOModel/Yi.Framework.DTOModel.csproj @@ -4,6 +4,10 @@ net6.0 + + + + diff --git a/Yi.Framework.Net6/Yi.Framework.DTOModel/loginDto.cs b/Yi.Framework.Net6/Yi.Framework.DTOModel/loginDto.cs deleted file mode 100644 index 456237b4..00000000 --- a/Yi.Framework.Net6/Yi.Framework.DTOModel/loginDto.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Yi.Framework.DTOModel -{ - public class loginDto - { - public string username { get; set; } - public string password { get; set; } - } -} diff --git a/Yi.Framework.Net6/Yi.Framework.DTOModel/menuDto.cs b/Yi.Framework.Net6/Yi.Framework.DTOModel/menuDto.cs deleted file mode 100644 index 4e52123b..00000000 --- a/Yi.Framework.Net6/Yi.Framework.DTOModel/menuDto.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Yi.Framework.Model.Models; - -namespace Yi.Framework.DTOModel -{ - public class menuDto - { - public int id { get; set; } - public string icon { get; set; } - public string router { get; set; } - public string menu_name { get; set; } - - public mould mould { get; set; } - } -} diff --git a/Yi.Framework.Net6/Yi.Framework.ElasticSearchProcessor/Yi.Framework.ElasticSearchProcessor.csproj b/Yi.Framework.Net6/Yi.Framework.ElasticSearchProcessor/Yi.Framework.ElasticSearchProcessor.csproj index d6bed982..ff210c47 100644 --- a/Yi.Framework.Net6/Yi.Framework.ElasticSearchProcessor/Yi.Framework.ElasticSearchProcessor.csproj +++ b/Yi.Framework.Net6/Yi.Framework.ElasticSearchProcessor/Yi.Framework.ElasticSearchProcessor.csproj @@ -10,11 +10,6 @@ - - PreserveNewest - true - PreserveNewest - PreserveNewest true diff --git a/Yi.Framework.Net6/Yi.Framework.Interface/IBaseService.cs b/Yi.Framework.Net6/Yi.Framework.Interface/IBaseService.cs deleted file mode 100644 index 2e9e8a03..00000000 --- a/Yi.Framework.Net6/Yi.Framework.Interface/IBaseService.cs +++ /dev/null @@ -1,87 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Text; -using System.Threading.Tasks; - -namespace Yi.Framework.Interface -{ - public interface IBaseService where T : class, new() - { - #region - //通过id得到实体 - #endregion - Task GetEntityById(int id); - - #region - //通过表达式得到实体 - #endregion - Task GetEntity(Expression> whereLambda); - - #region - //得到全部实体 - #endregion - Task> GetAllEntitiesAsync(); - - #region - //通过表达式得到实体 - #endregion - Task> GetEntitiesAsync(Expression> whereLambda); - - #region - //通过表达式得到实体,分页版本 - #endregion - Task GetCountAsync(Expression> whereLambda); - - #region - //通过表达式统计数量 - #endregion - IQueryable> GetGroup(Expression> whereLambda, Expression> groupByLambda); - - #region - //通过表达式分组 - #endregion - Task, int>> GetPageEntities(int pageSize, int pageIndex, Expression> whereLambda, Expression> orderByLambda, bool isAsc); - - #region - //添加实体 - #endregion - Task AddAsync(T entity); - - #region - //添加多个实体 - #endregion - Task AddAsync(IEnumerable entities); - - #region - //更新实体 - #endregion - Task UpdateAsync(T entity); - - #region - //更新多个实体 - #endregion - Task UpdateListAsync(IEnumerable entities); - - #region - //更新实体部分属性 - #endregion - Task DeleteAsync(T entity); - - #region - //删除实体 - #endregion - Task DeleteAsync(int id); - - #region - //通过id删除实体 - #endregion - Task DeleteAsync(IEnumerable ids); - - #region - //通过id列表删除多个实体 - #endregion - Task DeleteAsync(Expression> where); - } -} diff --git a/Yi.Framework.Net6/Yi.Framework.Interface/IMenuService.cs b/Yi.Framework.Net6/Yi.Framework.Interface/IMenuService.cs deleted file mode 100644 index aafce7e3..00000000 --- a/Yi.Framework.Net6/Yi.Framework.Interface/IMenuService.cs +++ /dev/null @@ -1,43 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Yi.Framework.Model.Models; - -namespace Yi.Framework.Interface -{ - public partial interface IMenuService:IBaseService - { - /// - /// 获取所有菜单,关联接口 - /// 这个是要递归的,但是要过滤掉删除的,所以,可以写一个通用过滤掉删除的方法 - /// - /// - Task GetMenuInMould(); - /// - /// 增 - /// 现在,top菜单只允许为一个 - /// - /// - Task AddTopMenu(menu _menu); - /// - /// 给一个菜单设置一个接口,Id1为菜单id,Id2为接口id - /// 用于给菜单设置接口 - /// - /// - Task SetMouldByMenu(int id1, int id2); - /// - /// 给一个菜单添加子节点(注意:添加,不是覆盖) - /// - /// - Task AddChildrenMenu(int menu_id, menu _children); - /// - /// 获取用户的目录菜单,不包含接口 - /// 用于账户信息页面,显示这个用户有哪些菜单,需要并列 - /// - /// - Task> GetTopMenusByTopMenuIds(List menuIds); - Task> GetTopMenuByUserId(int userId); - } -} diff --git a/Yi.Framework.Net6/Yi.Framework.Interface/IMouldService.cs b/Yi.Framework.Net6/Yi.Framework.Interface/IMouldService.cs deleted file mode 100644 index a9708a21..00000000 --- a/Yi.Framework.Net6/Yi.Framework.Interface/IMouldService.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Yi.Framework.Model.Models; - -namespace Yi.Framework.Interface -{ - public partial interface IMouldService : IBaseService - { - - - /// - /// 得到该接口属于哪个菜单的 - /// - /// - /// - Task GetMenuByMould(mould _mould); - - } -} diff --git a/Yi.Framework.Net6/Yi.Framework.Interface/IRoleService.cs b/Yi.Framework.Net6/Yi.Framework.Interface/IRoleService.cs deleted file mode 100644 index 5b0ea14e..00000000 --- a/Yi.Framework.Net6/Yi.Framework.Interface/IRoleService.cs +++ /dev/null @@ -1,47 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Yi.Framework.Model.Models; - -namespace Yi.Framework.Interface -{ - public partial interface IRoleService:IBaseService - { - - /// - /// 获取该角色的所有菜单 - /// - /// - /// - Task> GetMenusByRole(int roleId); - - /// - /// 给多个角色设置多个菜单 - /// - /// - /// - /// - Task SetMenusByRolesId(List menuIds, List roleIds); - /// - /// 获取多个用户的菜单,并列,不包含子菜单 - /// - /// - /// - Task> GetMenusByRoleId(List roleIds); - /// - /// 获取用户的角色 - /// - /// - /// - Task> GetRolesByUserId(int userId); - /// - /// 获取该角色的top菜单 - /// - /// - /// - Task> GetTopMenusByRoleId(int roleId); - - } -} diff --git a/Yi.Framework.Net6/Yi.Framework.Interface/IUserService.cs b/Yi.Framework.Net6/Yi.Framework.Interface/IUserService.cs index d9e8b91f..a8a3f8c5 100644 --- a/Yi.Framework.Net6/Yi.Framework.Interface/IUserService.cs +++ b/Yi.Framework.Net6/Yi.Framework.Interface/IUserService.cs @@ -3,84 +3,12 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; -using Yi.Framework.DTOModel; using Yi.Framework.Model.Models; +using Yi.Framework.Repository; namespace Yi.Framework.Interface { - public partial interface IUserService:IBaseService + public partial interface IUserService: IRepository { - - /// - /// 登录,传入_user需包含用户名与密码/角色 - /// - /// - Task Login(user _user); - - /// - /// 注册,需要检测是否用户名重复 - /// - /// - Task Register(user _user); - /// - /// 给多个用户设置多个角色 - /// - /// - /// - /// - Task SetRoleByUser(List roleIds, List userIds); - /// - /// 通过id获取用户信息,关联角色、菜单、子菜单、接口 - /// - /// - /// - Task GetUserById(int userId); - /// - /// email验证 - /// - /// - /// - Task EmailIsExsit(string emailAddress); - - /// - /// sms验证 - /// - /// - /// - Task PhoneIsExsit(string smsAddress); - - /// - /// 通过用户id,得到该用户的所有信息,关联角色 - /// - /// - /// - Task GetUserInRolesByHttpUser(int userId); - /// - /// 通过http获取用户id,得到该用户所有的菜单(递归的那种),把所有children为[]的值全部过滤成null,不要绑定mould - /// - /// - /// - Task GetMenuByHttpUser(List allMenuIds); - /// - /// 根据路由获取菜单 - /// - /// - /// - Task> GetAxiosByRouter(string router, List menuIds); - - - /// - /// 将登录用户的api保存的redis中 - /// - /// - /// - public bool SaveUserApi(int userId, List menus); - - /// - /// 通过用户id得到redis中菜单列表 - /// - /// - /// - public List GetCurrentMenuInfo(int userId); } } diff --git a/Yi.Framework.Net6/Yi.Framework.Interface/T4Iservice.cs b/Yi.Framework.Net6/Yi.Framework.Interface/T4Iservice.cs deleted file mode 100644 index bf91c56d..00000000 --- a/Yi.Framework.Net6/Yi.Framework.Interface/T4Iservice.cs +++ /dev/null @@ -1,40 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Yi.Framework.Model.Models; - -namespace Yi.Framework.Interface -{ - - public partial interface IMenuService:IBaseService - { - Task DelListByUpdateAsync(List _ids); - Task> GetAllEntitiesTrueAsync(); - } - - public partial interface IMouldService:IBaseService - { - Task DelListByUpdateAsync(List _ids); - Task> GetAllEntitiesTrueAsync(); - } - - public partial interface IRoleService:IBaseService - { - Task DelListByUpdateAsync(List _ids); - Task> GetAllEntitiesTrueAsync(); - } - - public partial interface IUserService:IBaseService - { - Task DelListByUpdateAsync(List _ids); - Task> GetAllEntitiesTrueAsync(); - } - - public partial interface IVisitService:IBaseService - { - Task DelListByUpdateAsync(List _ids); - Task> GetAllEntitiesTrueAsync(); - } -} diff --git a/Yi.Framework.Net6/Yi.Framework.Interface/T4Iservice.tt b/Yi.Framework.Net6/Yi.Framework.Interface/T4Iservice.tt deleted file mode 100644 index 0357f5a4..00000000 --- a/Yi.Framework.Net6/Yi.Framework.Interface/T4Iservice.tt +++ /dev/null @@ -1,43 +0,0 @@ -<#@ template debug="false" hostspecific="true" language="C#" #> -<#@ assembly name="System.Core" #> -<#@ import namespace="System.Linq" #> -<#@ import namespace="System.Text" #> -<#@ import namespace="System.IO" #> -<#@ import namespace="System.Collections.Generic" #> -<#@ output extension=".cs" #> -<# - string solutionsPath = Host.ResolveAssemblyReference("$(SolutionDir)");//获取解决方案路径 - string dirPath= Path.Combine(solutionsPath,@"Yi.Framework.Model\Models\"); - DirectoryInfo dir = new DirectoryInfo(dirPath); - FileInfo[] finfo = dir.GetFiles(); - string filenames = string.Empty; - List filenameList = new List(); - for (int i = 0; i < finfo.Length; i++) - { - filenames = finfo[i].Name ; - string[] fname=filenames.Split('.'); - filenameList.Add(fname[0]); - } - - -#> -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Yi.Framework.Model.Models; - -namespace Yi.Framework.Interface -{ - <# foreach(string k in filenameList){ - string fn= k.Substring(0,1).ToUpper()+k.Substring(1); - #> - - public partial interface I<#= fn #>Service:IBaseService<<#= k #>> - { - Task DelListByUpdateAsync(List _ids); - Task>> GetAllEntitiesTrueAsync(); - } -<# } #> -} diff --git a/Yi.Framework.Net6/Yi.Framework.Interface/Yi.Framework.Interface.csproj b/Yi.Framework.Net6/Yi.Framework.Interface/Yi.Framework.Interface.csproj index 300a2261..1877687a 100644 --- a/Yi.Framework.Net6/Yi.Framework.Interface/Yi.Framework.Interface.csproj +++ b/Yi.Framework.Net6/Yi.Framework.Interface/Yi.Framework.Interface.csproj @@ -11,25 +11,11 @@ - - - - - T4Iservice.cs - TextTemplatingFileGenerator - + - - - True - True - T4IService.tt - - - diff --git a/Yi.Framework.Net6/Yi.Framework.Language/LocalLanguage.cs b/Yi.Framework.Net6/Yi.Framework.Language/LocalLanguage.cs new file mode 100644 index 00000000..b8ffbe5e --- /dev/null +++ b/Yi.Framework.Net6/Yi.Framework.Language/LocalLanguage.cs @@ -0,0 +1,7 @@ +namespace Yi.Framework.Language +{ + public class LocalLanguage + { + + } +} \ No newline at end of file diff --git a/Yi.Framework.Net6/Yi.Framework.Language/LocalLanguage.en.resx b/Yi.Framework.Net6/Yi.Framework.Language/LocalLanguage.en.resx new file mode 100644 index 00000000..212b1e32 --- /dev/null +++ b/Yi.Framework.Net6/Yi.Framework.Language/LocalLanguage.en.resx @@ -0,0 +1,171 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Internal interaction error + + + fail + + + Login failed, please check your user name and password + + + Login successful + + + Logout successful + + + The current menu already exists + + + Login failed! The user does not have any roles + + + Original password error + + + The current role already exists + + + success + + + Refreshtoken expired, refresh failed! + + + Token expiration + + + Accesstoken and refreshtoken are refreshed successfully! + + + Unauthorized + + + User changed + + + user does not exist + + + User already registered + + \ No newline at end of file diff --git a/Yi.Framework.Net6/Yi.Framework.Language/LocalLanguage.zh.resx b/Yi.Framework.Net6/Yi.Framework.Language/LocalLanguage.zh.resx new file mode 100644 index 00000000..e18b038c --- /dev/null +++ b/Yi.Framework.Net6/Yi.Framework.Language/LocalLanguage.zh.resx @@ -0,0 +1,171 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 内部交互错误 + + + 失败 + + + 登录失败,请检查你的用户名与密码 + + + 登录成功 + + + 登出成功 + + + 当前菜单已存在 + + + 登录失败!该用户未拥有任何角色 + + + 原密码错误 + + + 当前角色已存在 + + + 成功 + + + RefreshToken过期,刷新失败! + + + 令牌过期 + + + AccessToken, RefreshToken刷新成功! + + + 未授权 + + + 用户已更改 + + + 用户不存在 + + + 用户已经注册 + + \ No newline at end of file diff --git a/Yi.Framework.Net6/Yi.Framework.Language/Yi.Framework.Language.csproj b/Yi.Framework.Net6/Yi.Framework.Language/Yi.Framework.Language.csproj new file mode 100644 index 00000000..132c02c5 --- /dev/null +++ b/Yi.Framework.Net6/Yi.Framework.Language/Yi.Framework.Language.csproj @@ -0,0 +1,9 @@ + + + + net6.0 + enable + enable + + + diff --git a/Yi.Framework.Net6/Yi.Framework.Model/BaseModels/baseModel.cs b/Yi.Framework.Net6/Yi.Framework.Model/BaseModels/baseModel.cs deleted file mode 100644 index 0229e997..00000000 --- a/Yi.Framework.Net6/Yi.Framework.Model/BaseModels/baseModel.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; -using System.ComponentModel.DataAnnotations.Schema; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Yi.Framework.Model.Models -{ - public class baseModel - { - [Key] - [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] - public T id { get; set; } - public int is_delete { get; set; } - } -} diff --git a/Yi.Framework.Net6/Yi.Framework.Model/BaseModels/loopModel.cs b/Yi.Framework.Net6/Yi.Framework.Model/BaseModels/loopModel.cs deleted file mode 100644 index cece5646..00000000 --- a/Yi.Framework.Net6/Yi.Framework.Model/BaseModels/loopModel.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations.Schema; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Yi.Framework.Model.Models -{ - public class loopModel:baseModel - { - public int is_top { get; set; } - public int sort { get; set; } - public int is_show { get; set; } - public int parentId { get; set; } - - [NotMapped] - public IList children { get; set; } - } -} diff --git a/Yi.Framework.Net6/Yi.Framework.Model/DataContext.cs b/Yi.Framework.Net6/Yi.Framework.Model/DataContext.cs deleted file mode 100644 index 40cd5730..00000000 --- a/Yi.Framework.Net6/Yi.Framework.Model/DataContext.cs +++ /dev/null @@ -1,55 +0,0 @@ -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Options; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Yi.Framework.Common.Const; -using Yi.Framework.Common.IOCOptions; -using Yi.Framework.Model.Models; - -namespace Yi.Framework.Model -{ - //Add-Migration yi-1 - //Update-Database yi-1 - public partial class DataContext : DbContext - { - //private readonly IOptionsMonitor _optionsMonitor; - public static string _connStr; - public static string DbSelect = DbConst.Mysql; - //public DataContext(IOptionsMonitor optionsMonitor) - //{ - // _optionsMonitor = optionsMonitor; - // _connStr = _optionsMonitor.CurrentValue.WriteUrl; - //} - public DbContext ToWriteOrRead(string connstr) - { - _connStr = connstr; - return this; - } - - - protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) - { - if (!optionsBuilder.IsConfigured) - { - switch (DbSelect) - { - case DbConst.Mysql: - var serverVersion = new MySqlServerVersion(new Version(8, 0, 21)); - optionsBuilder.UseMySql(_connStr, serverVersion); break; - case DbConst.Sqlite: - optionsBuilder.UseSqlite(_connStr); break; - case DbConst.Sqlserver: - optionsBuilder.UseSqlServer(_connStr);break; - case DbConst.Oracle: - optionsBuilder.UseOracle(_connStr);break; - default: - Console.WriteLine("错误!请确保你选择了正确的数据库!");break; - } - } - } - - } -} diff --git a/Yi.Framework.Net6/Yi.Framework.Model/Migrations/20220221034128_yi-1.Designer.cs b/Yi.Framework.Net6/Yi.Framework.Model/Migrations/20220221034128_yi-1.Designer.cs deleted file mode 100644 index 0048a127..00000000 --- a/Yi.Framework.Net6/Yi.Framework.Model/Migrations/20220221034128_yi-1.Designer.cs +++ /dev/null @@ -1,239 +0,0 @@ -// -using System; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.EntityFrameworkCore.Migrations; -using Microsoft.EntityFrameworkCore.Storage.ValueConversion; -using Yi.Framework.Model; - -#nullable disable - -namespace Yi.Framework.Model.Migrations -{ - [DbContext(typeof(DataContext))] - [Migration("20220221034128_yi-1")] - partial class yi1 - { - protected override void BuildTargetModel(ModelBuilder modelBuilder) - { -#pragma warning disable 612, 618 - modelBuilder - .HasAnnotation("ProductVersion", "6.0.1") - .HasAnnotation("Relational:MaxIdentifierLength", 64); - - modelBuilder.Entity("menurole", b => - { - b.Property("menusid") - .HasColumnType("int"); - - b.Property("rolesid") - .HasColumnType("int"); - - b.HasKey("menusid", "rolesid"); - - b.HasIndex("rolesid"); - - b.ToTable("menurole"); - }); - - modelBuilder.Entity("roleuser", b => - { - b.Property("rolesid") - .HasColumnType("int"); - - b.Property("usersid") - .HasColumnType("int"); - - b.HasKey("rolesid", "usersid"); - - b.HasIndex("usersid"); - - b.ToTable("roleuser"); - }); - - modelBuilder.Entity("Yi.Framework.Model.Models.menu", b => - { - b.Property("id") - .ValueGeneratedOnAdd() - .HasColumnType("int"); - - b.Property("icon") - .HasColumnType("longtext"); - - b.Property("is_delete") - .HasColumnType("int"); - - b.Property("is_show") - .HasColumnType("int"); - - b.Property("is_top") - .HasColumnType("int"); - - b.Property("menu_name") - .HasColumnType("longtext"); - - b.Property("mouldid") - .HasColumnType("int"); - - b.Property("parentId") - .HasColumnType("int"); - - b.Property("router") - .HasColumnType("longtext"); - - b.Property("sort") - .HasColumnType("int"); - - b.HasKey("id"); - - b.HasIndex("mouldid"); - - b.ToTable("menu"); - }); - - modelBuilder.Entity("Yi.Framework.Model.Models.mould", b => - { - b.Property("id") - .ValueGeneratedOnAdd() - .HasColumnType("int"); - - b.Property("is_delete") - .HasColumnType("int"); - - b.Property("mould_name") - .HasColumnType("longtext"); - - b.Property("url") - .HasColumnType("longtext"); - - b.HasKey("id"); - - b.ToTable("mould"); - }); - - modelBuilder.Entity("Yi.Framework.Model.Models.role", b => - { - b.Property("id") - .ValueGeneratedOnAdd() - .HasColumnType("int"); - - b.Property("introduce") - .HasColumnType("longtext"); - - b.Property("is_delete") - .HasColumnType("int"); - - b.Property("role_name") - .HasColumnType("longtext"); - - b.HasKey("id"); - - b.ToTable("role"); - }); - - modelBuilder.Entity("Yi.Framework.Model.Models.user", b => - { - b.Property("id") - .ValueGeneratedOnAdd() - .HasColumnType("int"); - - b.Property("address") - .HasColumnType("longtext"); - - b.Property("age") - .HasColumnType("int"); - - b.Property("email") - .HasColumnType("longtext"); - - b.Property("icon") - .HasColumnType("longtext"); - - b.Property("introduction") - .HasColumnType("longtext"); - - b.Property("ip") - .HasColumnType("longtext"); - - b.Property("is_delete") - .HasColumnType("int"); - - b.Property("nick") - .HasColumnType("longtext"); - - b.Property("password") - .HasColumnType("longtext"); - - b.Property("phone") - .HasColumnType("longtext"); - - b.Property("username") - .HasColumnType("longtext"); - - b.HasKey("id"); - - b.ToTable("user"); - }); - - modelBuilder.Entity("Yi.Framework.Model.Models.visit", b => - { - b.Property("id") - .ValueGeneratedOnAdd() - .HasColumnType("int"); - - b.Property("is_delete") - .HasColumnType("int"); - - b.Property("num") - .HasColumnType("int"); - - b.Property("time") - .HasColumnType("datetime(6)"); - - b.HasKey("id"); - - b.ToTable("visit"); - }); - - modelBuilder.Entity("menurole", b => - { - b.HasOne("Yi.Framework.Model.Models.menu", null) - .WithMany() - .HasForeignKey("menusid") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.HasOne("Yi.Framework.Model.Models.role", null) - .WithMany() - .HasForeignKey("rolesid") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - }); - - modelBuilder.Entity("roleuser", b => - { - b.HasOne("Yi.Framework.Model.Models.role", null) - .WithMany() - .HasForeignKey("rolesid") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.HasOne("Yi.Framework.Model.Models.user", null) - .WithMany() - .HasForeignKey("usersid") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - }); - - modelBuilder.Entity("Yi.Framework.Model.Models.menu", b => - { - b.HasOne("Yi.Framework.Model.Models.mould", "mould") - .WithMany() - .HasForeignKey("mouldid"); - - b.Navigation("mould"); - }); -#pragma warning restore 612, 618 - } - } -} diff --git a/Yi.Framework.Net6/Yi.Framework.Model/Migrations/20220221034128_yi-1.cs b/Yi.Framework.Net6/Yi.Framework.Model/Migrations/20220221034128_yi-1.cs deleted file mode 100644 index f28c03c1..00000000 --- a/Yi.Framework.Net6/Yi.Framework.Model/Migrations/20220221034128_yi-1.cs +++ /dev/null @@ -1,221 +0,0 @@ -using System; -using Microsoft.EntityFrameworkCore.Metadata; -using Microsoft.EntityFrameworkCore.Migrations; - -#nullable disable - -namespace Yi.Framework.Model.Migrations -{ - public partial class yi1 : Migration - { - protected override void Up(MigrationBuilder migrationBuilder) - { - migrationBuilder.AlterDatabase() - .Annotation("MySql:CharSet", "utf8mb4"); - - migrationBuilder.CreateTable( - name: "mould", - columns: table => new - { - id = table.Column(type: "int", nullable: false) - .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), - mould_name = table.Column(type: "longtext", nullable: true) - .Annotation("MySql:CharSet", "utf8mb4"), - url = table.Column(type: "longtext", nullable: true) - .Annotation("MySql:CharSet", "utf8mb4"), - is_delete = table.Column(type: "int", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_mould", x => x.id); - }) - .Annotation("MySql:CharSet", "utf8mb4"); - - migrationBuilder.CreateTable( - name: "role", - columns: table => new - { - id = table.Column(type: "int", nullable: false) - .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), - role_name = table.Column(type: "longtext", nullable: true) - .Annotation("MySql:CharSet", "utf8mb4"), - introduce = table.Column(type: "longtext", nullable: true) - .Annotation("MySql:CharSet", "utf8mb4"), - is_delete = table.Column(type: "int", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_role", x => x.id); - }) - .Annotation("MySql:CharSet", "utf8mb4"); - - migrationBuilder.CreateTable( - name: "user", - columns: table => new - { - id = table.Column(type: "int", nullable: false) - .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), - username = table.Column(type: "longtext", nullable: true) - .Annotation("MySql:CharSet", "utf8mb4"), - password = table.Column(type: "longtext", nullable: true) - .Annotation("MySql:CharSet", "utf8mb4"), - icon = table.Column(type: "longtext", nullable: true) - .Annotation("MySql:CharSet", "utf8mb4"), - nick = table.Column(type: "longtext", nullable: true) - .Annotation("MySql:CharSet", "utf8mb4"), - email = table.Column(type: "longtext", nullable: true) - .Annotation("MySql:CharSet", "utf8mb4"), - ip = table.Column(type: "longtext", nullable: true) - .Annotation("MySql:CharSet", "utf8mb4"), - age = table.Column(type: "int", nullable: true), - introduction = table.Column(type: "longtext", nullable: true) - .Annotation("MySql:CharSet", "utf8mb4"), - address = table.Column(type: "longtext", nullable: true) - .Annotation("MySql:CharSet", "utf8mb4"), - phone = table.Column(type: "longtext", nullable: true) - .Annotation("MySql:CharSet", "utf8mb4"), - is_delete = table.Column(type: "int", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_user", x => x.id); - }) - .Annotation("MySql:CharSet", "utf8mb4"); - - migrationBuilder.CreateTable( - name: "visit", - columns: table => new - { - id = table.Column(type: "int", nullable: false) - .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), - time = table.Column(type: "datetime(6)", nullable: false), - num = table.Column(type: "int", nullable: false), - is_delete = table.Column(type: "int", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_visit", x => x.id); - }) - .Annotation("MySql:CharSet", "utf8mb4"); - - migrationBuilder.CreateTable( - name: "menu", - columns: table => new - { - id = table.Column(type: "int", nullable: false) - .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), - icon = table.Column(type: "longtext", nullable: true) - .Annotation("MySql:CharSet", "utf8mb4"), - router = table.Column(type: "longtext", nullable: true) - .Annotation("MySql:CharSet", "utf8mb4"), - menu_name = table.Column(type: "longtext", nullable: true) - .Annotation("MySql:CharSet", "utf8mb4"), - mouldid = table.Column(type: "int", nullable: true), - is_delete = table.Column(type: "int", nullable: false), - is_top = table.Column(type: "int", nullable: false), - sort = table.Column(type: "int", nullable: false), - is_show = table.Column(type: "int", nullable: false), - parentId = table.Column(type: "int", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_menu", x => x.id); - table.ForeignKey( - name: "FK_menu_mould_mouldid", - column: x => x.mouldid, - principalTable: "mould", - principalColumn: "id"); - }) - .Annotation("MySql:CharSet", "utf8mb4"); - - migrationBuilder.CreateTable( - name: "roleuser", - columns: table => new - { - rolesid = table.Column(type: "int", nullable: false), - usersid = table.Column(type: "int", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_roleuser", x => new { x.rolesid, x.usersid }); - table.ForeignKey( - name: "FK_roleuser_role_rolesid", - column: x => x.rolesid, - principalTable: "role", - principalColumn: "id", - onDelete: ReferentialAction.Cascade); - table.ForeignKey( - name: "FK_roleuser_user_usersid", - column: x => x.usersid, - principalTable: "user", - principalColumn: "id", - onDelete: ReferentialAction.Cascade); - }) - .Annotation("MySql:CharSet", "utf8mb4"); - - migrationBuilder.CreateTable( - name: "menurole", - columns: table => new - { - menusid = table.Column(type: "int", nullable: false), - rolesid = table.Column(type: "int", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_menurole", x => new { x.menusid, x.rolesid }); - table.ForeignKey( - name: "FK_menurole_menu_menusid", - column: x => x.menusid, - principalTable: "menu", - principalColumn: "id", - onDelete: ReferentialAction.Cascade); - table.ForeignKey( - name: "FK_menurole_role_rolesid", - column: x => x.rolesid, - principalTable: "role", - principalColumn: "id", - onDelete: ReferentialAction.Cascade); - }) - .Annotation("MySql:CharSet", "utf8mb4"); - - migrationBuilder.CreateIndex( - name: "IX_menu_mouldid", - table: "menu", - column: "mouldid"); - - migrationBuilder.CreateIndex( - name: "IX_menurole_rolesid", - table: "menurole", - column: "rolesid"); - - migrationBuilder.CreateIndex( - name: "IX_roleuser_usersid", - table: "roleuser", - column: "usersid"); - } - - protected override void Down(MigrationBuilder migrationBuilder) - { - migrationBuilder.DropTable( - name: "menurole"); - - migrationBuilder.DropTable( - name: "roleuser"); - - migrationBuilder.DropTable( - name: "visit"); - - migrationBuilder.DropTable( - name: "menu"); - - migrationBuilder.DropTable( - name: "role"); - - migrationBuilder.DropTable( - name: "user"); - - migrationBuilder.DropTable( - name: "mould"); - } - } -} diff --git a/Yi.Framework.Net6/Yi.Framework.Model/Migrations/DataContextModelSnapshot.cs b/Yi.Framework.Net6/Yi.Framework.Model/Migrations/DataContextModelSnapshot.cs deleted file mode 100644 index e22dc20e..00000000 --- a/Yi.Framework.Net6/Yi.Framework.Model/Migrations/DataContextModelSnapshot.cs +++ /dev/null @@ -1,237 +0,0 @@ -// -using System; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.EntityFrameworkCore.Storage.ValueConversion; -using Yi.Framework.Model; - -#nullable disable - -namespace Yi.Framework.Model.Migrations -{ - [DbContext(typeof(DataContext))] - partial class DataContextModelSnapshot : ModelSnapshot - { - protected override void BuildModel(ModelBuilder modelBuilder) - { -#pragma warning disable 612, 618 - modelBuilder - .HasAnnotation("ProductVersion", "6.0.1") - .HasAnnotation("Relational:MaxIdentifierLength", 64); - - modelBuilder.Entity("menurole", b => - { - b.Property("menusid") - .HasColumnType("int"); - - b.Property("rolesid") - .HasColumnType("int"); - - b.HasKey("menusid", "rolesid"); - - b.HasIndex("rolesid"); - - b.ToTable("menurole"); - }); - - modelBuilder.Entity("roleuser", b => - { - b.Property("rolesid") - .HasColumnType("int"); - - b.Property("usersid") - .HasColumnType("int"); - - b.HasKey("rolesid", "usersid"); - - b.HasIndex("usersid"); - - b.ToTable("roleuser"); - }); - - modelBuilder.Entity("Yi.Framework.Model.Models.menu", b => - { - b.Property("id") - .ValueGeneratedOnAdd() - .HasColumnType("int"); - - b.Property("icon") - .HasColumnType("longtext"); - - b.Property("is_delete") - .HasColumnType("int"); - - b.Property("is_show") - .HasColumnType("int"); - - b.Property("is_top") - .HasColumnType("int"); - - b.Property("menu_name") - .HasColumnType("longtext"); - - b.Property("mouldid") - .HasColumnType("int"); - - b.Property("parentId") - .HasColumnType("int"); - - b.Property("router") - .HasColumnType("longtext"); - - b.Property("sort") - .HasColumnType("int"); - - b.HasKey("id"); - - b.HasIndex("mouldid"); - - b.ToTable("menu"); - }); - - modelBuilder.Entity("Yi.Framework.Model.Models.mould", b => - { - b.Property("id") - .ValueGeneratedOnAdd() - .HasColumnType("int"); - - b.Property("is_delete") - .HasColumnType("int"); - - b.Property("mould_name") - .HasColumnType("longtext"); - - b.Property("url") - .HasColumnType("longtext"); - - b.HasKey("id"); - - b.ToTable("mould"); - }); - - modelBuilder.Entity("Yi.Framework.Model.Models.role", b => - { - b.Property("id") - .ValueGeneratedOnAdd() - .HasColumnType("int"); - - b.Property("introduce") - .HasColumnType("longtext"); - - b.Property("is_delete") - .HasColumnType("int"); - - b.Property("role_name") - .HasColumnType("longtext"); - - b.HasKey("id"); - - b.ToTable("role"); - }); - - modelBuilder.Entity("Yi.Framework.Model.Models.user", b => - { - b.Property("id") - .ValueGeneratedOnAdd() - .HasColumnType("int"); - - b.Property("address") - .HasColumnType("longtext"); - - b.Property("age") - .HasColumnType("int"); - - b.Property("email") - .HasColumnType("longtext"); - - b.Property("icon") - .HasColumnType("longtext"); - - b.Property("introduction") - .HasColumnType("longtext"); - - b.Property("ip") - .HasColumnType("longtext"); - - b.Property("is_delete") - .HasColumnType("int"); - - b.Property("nick") - .HasColumnType("longtext"); - - b.Property("password") - .HasColumnType("longtext"); - - b.Property("phone") - .HasColumnType("longtext"); - - b.Property("username") - .HasColumnType("longtext"); - - b.HasKey("id"); - - b.ToTable("user"); - }); - - modelBuilder.Entity("Yi.Framework.Model.Models.visit", b => - { - b.Property("id") - .ValueGeneratedOnAdd() - .HasColumnType("int"); - - b.Property("is_delete") - .HasColumnType("int"); - - b.Property("num") - .HasColumnType("int"); - - b.Property("time") - .HasColumnType("datetime(6)"); - - b.HasKey("id"); - - b.ToTable("visit"); - }); - - modelBuilder.Entity("menurole", b => - { - b.HasOne("Yi.Framework.Model.Models.menu", null) - .WithMany() - .HasForeignKey("menusid") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.HasOne("Yi.Framework.Model.Models.role", null) - .WithMany() - .HasForeignKey("rolesid") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - }); - - modelBuilder.Entity("roleuser", b => - { - b.HasOne("Yi.Framework.Model.Models.role", null) - .WithMany() - .HasForeignKey("rolesid") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.HasOne("Yi.Framework.Model.Models.user", null) - .WithMany() - .HasForeignKey("usersid") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - }); - - modelBuilder.Entity("Yi.Framework.Model.Models.menu", b => - { - b.HasOne("Yi.Framework.Model.Models.mould", "mould") - .WithMany() - .HasForeignKey("mouldid"); - - b.Navigation("mould"); - }); -#pragma warning restore 612, 618 - } - } -} diff --git a/Yi.Framework.Net6/Yi.Framework.Model/ModelFactory/DbContextExtend.cs b/Yi.Framework.Net6/Yi.Framework.Model/ModelFactory/DbContextExtend.cs deleted file mode 100644 index d4cb3846..00000000 --- a/Yi.Framework.Net6/Yi.Framework.Model/ModelFactory/DbContextExtend.cs +++ /dev/null @@ -1,23 +0,0 @@ -using Microsoft.EntityFrameworkCore; -using System; -using System.Collections.Generic; -using System.Text; - -namespace Yi.Framework.Model.ModelFactory -{ - public static class DbContextExtend - { - public static DbContext ToWriteOrRead(this DbContext dbContext, string conn) - { - if (dbContext is DataContext) - { - - var context= (DataContext)dbContext; // context 是 EFCoreContext 实例; - - return context.ToWriteOrRead(conn); - } - else - throw new Exception(); - } - } -} diff --git a/Yi.Framework.Net6/Yi.Framework.Model/ModelFactory/DbContextFactory.cs b/Yi.Framework.Net6/Yi.Framework.Model/ModelFactory/DbContextFactory.cs deleted file mode 100644 index a156afdf..00000000 --- a/Yi.Framework.Net6/Yi.Framework.Model/ModelFactory/DbContextFactory.cs +++ /dev/null @@ -1,100 +0,0 @@ -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Options; -using System; -using System.Collections.Generic; -using System.Text; -using Yi.Framework.Common.Enum; -using Yi.Framework.Common.IOCOptions; - -namespace Yi.Framework.Model.ModelFactory -{ - public class DbContextFactory : IDbContextFactory - { - - private DbContext _Context = null; - - private DbConnOptions _readAndWrite = null; - - public static bool MutiDB_Enabled = false; - //private static int _iSeed = 0;//应该long - - /// - ///能把链接信息也注入进来 - ///需要IOptionsMonitor - /// - /// - public DbContextFactory(DbContext context, IOptionsMonitor options) - { - _readAndWrite = options.CurrentValue; - this._Context = context; - } - public DbContext ConnWriteOrRead(WriteAndReadEnum writeAndRead) - { - //判断枚举,不同的枚举可以创建不同的Context 或者更换Context链接; - if (MutiDB_Enabled) - { - switch (writeAndRead) - { - case WriteAndReadEnum.Write: - ToWrite(); - break; //选择链接//更换_Context链接 //选择链接 - case WriteAndReadEnum.Read: - ToRead(); - break; //选择链接//更换_Context链接 - default: - break; - } - } - else - { - ToWrite(); - } - - return _Context; - } - - /// - /// 更换成主库连接 - /// - /// - private void ToWrite() - { - string conn = _readAndWrite.WriteUrl; - //_Context.Database.GetDbConnection().; - _Context.ToWriteOrRead(conn); - } - - - private static int _iSeed = 0; - - /// - /// 更换成主库连接 - /// - /// ///策略---数据库查询的负载均衡 - /// - /// - private void ToRead() - { - string conn = string.Empty; - { - // //随机 - //int Count= _readAndWrite.ReadConnectionList.Count; - //int index= new Random().Next(0, Count); - //conn = _readAndWrite.ReadConnectionList[index]; - } - { - //来一个轮询 - conn = this._readAndWrite.ReadUrl[_iSeed++ % this._readAndWrite.ReadUrl.Count];//轮询; - } - { - ///是不是可以直接配置到配置文件里面 - } - _Context.ToWriteOrRead(conn); - } - - //public DbContext CreateContext() - //{ - - //} - } -} diff --git a/Yi.Framework.Net6/Yi.Framework.Model/ModelFactory/IDbContextFactory.cs b/Yi.Framework.Net6/Yi.Framework.Model/ModelFactory/IDbContextFactory.cs deleted file mode 100644 index 818bca67..00000000 --- a/Yi.Framework.Net6/Yi.Framework.Model/ModelFactory/IDbContextFactory.cs +++ /dev/null @@ -1,13 +0,0 @@ -using Microsoft.EntityFrameworkCore; -using System; -using System.Collections.Generic; -using System.Text; -using Yi.Framework.Common.Enum; - -namespace Yi.Framework.Model.ModelFactory -{ - public interface IDbContextFactory - { - public DbContext ConnWriteOrRead(WriteAndReadEnum writeAndRead); - } -} diff --git a/Yi.Framework.Net6/Yi.Framework.Model/Models/menu.cs b/Yi.Framework.Net6/Yi.Framework.Model/Models/menu.cs deleted file mode 100644 index 954999ab..00000000 --- a/Yi.Framework.Net6/Yi.Framework.Model/Models/menu.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Yi.Framework.Common.Models; - -namespace Yi.Framework.Model.Models -{ - public class menu :loopModel,ITreeModel - { - public string icon { get; set; } - public string router { get; set; } - public string menu_name { get; set; } - - public List roles { get; set; } - public mould mould { get; set; } - - - } -} diff --git a/Yi.Framework.Net6/Yi.Framework.Model/Models/mould.cs b/Yi.Framework.Net6/Yi.Framework.Model/Models/mould.cs deleted file mode 100644 index f86a5489..00000000 --- a/Yi.Framework.Net6/Yi.Framework.Model/Models/mould.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Yi.Framework.Model.Models -{ - public class mould:baseModel - { - public string mould_name { get; set; } - public string url { get; set; } - } -} diff --git a/Yi.Framework.Net6/Yi.Framework.Model/Models/role.cs b/Yi.Framework.Net6/Yi.Framework.Model/Models/role.cs deleted file mode 100644 index 8516124f..00000000 --- a/Yi.Framework.Net6/Yi.Framework.Model/Models/role.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Yi.Framework.Model.Models -{ - public class role:baseModel - { - public string role_name { get; set; } - public string introduce { get; set; } - - - public List menus { get; set; } - public List users { get; set; } - } -} diff --git a/Yi.Framework.Net6/Yi.Framework.Model/Models/user.cs b/Yi.Framework.Net6/Yi.Framework.Model/Models/user.cs index 58857e36..c7348171 100644 --- a/Yi.Framework.Net6/Yi.Framework.Model/Models/user.cs +++ b/Yi.Framework.Net6/Yi.Framework.Model/Models/user.cs @@ -7,21 +7,19 @@ using System.Threading.Tasks; namespace Yi.Framework.Model.Models { - public class user:baseModel + public class User { - public string username { get; set; } - public string password { get; set; } - public string icon { get; set; } - public string nick { get; set; } - public string email { get; set; } - public string ip { get; set; } - public int? age { get; set; } - public string introduction { get; set; } - public string address { get; set; } - public string phone { get; set; } - + public int Id { get; set; } + public string Username { get; set; } + public string Password { get; set; } + public string Icon { get; set; } + public string Nick { get; set; } + public string Email { get; set; } + public string Ip { get; set; } + public int? Age { get; set; } + public string Introduction { get; set; } + public string Address { get; set; } + public string Phone { get; set; } - public List roles { get; set; } - } } diff --git a/Yi.Framework.Net6/Yi.Framework.Model/Models/visit.cs b/Yi.Framework.Net6/Yi.Framework.Model/Models/visit.cs deleted file mode 100644 index 845b753c..00000000 --- a/Yi.Framework.Net6/Yi.Framework.Model/Models/visit.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Yi.Framework.Model.Models -{ - public class visit:baseModel - { - public DateTime time { get; set; } - public int num { get; set; } - } -} diff --git a/Yi.Framework.Net6/Yi.Framework.Model/T4DataContext.cs b/Yi.Framework.Net6/Yi.Framework.Model/T4DataContext.cs deleted file mode 100644 index 071e4b24..00000000 --- a/Yi.Framework.Net6/Yi.Framework.Model/T4DataContext.cs +++ /dev/null @@ -1,18 +0,0 @@ -using Microsoft.EntityFrameworkCore; -using System; -using System.Collections.Generic; -using System.Text; -using Yi.Framework.Model.Models; - -namespace Yi.Framework.Model -{ - public partial class DataContext :DbContext - { - public DbSet menu { get; set; } - public DbSet mould { get; set; } - public DbSet role { get; set; } - public DbSet user { get; set; } - public DbSet visit { get; set; } - } -} - diff --git a/Yi.Framework.Net6/Yi.Framework.Model/T4DataContext.tt b/Yi.Framework.Net6/Yi.Framework.Model/T4DataContext.tt deleted file mode 100644 index ecc01244..00000000 --- a/Yi.Framework.Net6/Yi.Framework.Model/T4DataContext.tt +++ /dev/null @@ -1,40 +0,0 @@ -<#@ template debug="false" hostspecific="true" language="C#" #> -<#@ assembly name="System.Core" #> -<#@ import namespace="System.Linq" #> -<#@ import namespace="System.Text" #> -<#@ import namespace="System.IO" #> -<#@ import namespace="System.Collections.Generic" #> -<#@ output extension=".cs" #> -<# - string solutionsPath = Host.ResolveAssemblyReference("$(SolutionDir)");//获取解决方案路径 - string dirPath= Path.Combine(solutionsPath,@"Yi.Framework.Model\Models\"); - DirectoryInfo dir = new DirectoryInfo(dirPath); - FileInfo[] finfo = dir.GetFiles(); - string filenames = string.Empty; - List filenameList = new List(); - for (int i = 0; i < finfo.Length; i++) - { - filenames = finfo[i].Name ; - string[] f=filenames.Split('.'); - filenameList.Add(f[0]); - } - - -#> -using Microsoft.EntityFrameworkCore; -using System; -using System.Collections.Generic; -using System.Text; -using Yi.Framework.Model.Models; - -namespace Yi.Framework.Model -{ - public partial class DataContext :DbContext - { -<# foreach(string k in filenameList){ - #> - public DbSet<<#=k #>> <#=k #> { get; set; } -<# } #> - } -} - diff --git a/Yi.Framework.Net6/Yi.Framework.Model/Yi.Framework.Model.csproj b/Yi.Framework.Net6/Yi.Framework.Model/Yi.Framework.Model.csproj index 6b3bd2f6..c7adb2fb 100644 --- a/Yi.Framework.Net6/Yi.Framework.Model/Yi.Framework.Model.csproj +++ b/Yi.Framework.Net6/Yi.Framework.Model/Yi.Framework.Model.csproj @@ -5,15 +5,7 @@ - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - @@ -25,10 +17,6 @@ TextTemplatingFileGenerator T4DaraContext.cs - - TextTemplatingFileGenerator - T4DataContext.cs - @@ -41,11 +29,11 @@ True T4DaraContext.tt - - True - True - T4DataContext.tt - + + + + + diff --git a/Yi.Framework.Net6/Yi.Framework.OcelotGateway/Builder/AbstractBuilder.cs b/Yi.Framework.Net6/Yi.Framework.OcelotGateway/Builder/AbstractBuilder.cs new file mode 100644 index 00000000..29f7946d --- /dev/null +++ b/Yi.Framework.Net6/Yi.Framework.OcelotGateway/Builder/AbstractBuilder.cs @@ -0,0 +1,25 @@ +namespace Yi.Framework.OcelotGateway.Builder +{ + public abstract class AbstractBuilder + { + + public abstract void Invoke(DataContext data); + + private AbstractBuilder? NextBuilder=null; + + + public void SetNext(AbstractBuilder? nextBuilder) + { + this.NextBuilder = nextBuilder; + } + + public void Next( DataContext data) + { + if (NextBuilder != null) + { + this.NextBuilder!.Invoke(data!); + } + + } + } +} diff --git a/Yi.Framework.Net6/Yi.Framework.OcelotGateway/Builder/AccoutBuilder.cs b/Yi.Framework.Net6/Yi.Framework.OcelotGateway/Builder/AccoutBuilder.cs new file mode 100644 index 00000000..871a320e --- /dev/null +++ b/Yi.Framework.Net6/Yi.Framework.OcelotGateway/Builder/AccoutBuilder.cs @@ -0,0 +1,22 @@ + +using Yi.Framework.Common.Models; + +namespace Yi.Framework.OcelotGateway.Builder +{ + public class AccoutBuilder : AbstractBuilder + { + + public override void Invoke(DataContext data) + { + //直接放行,并需要鉴权 + if (data!.AccountPathList!.Contains(data.Path!)) + { + data.Result = Result.Success(); + } + else//剩下的这个,就是最后真正的业务判断 + { + base.Next(data); + } + } + } +} diff --git a/Yi.Framework.Net6/Yi.Framework.OcelotGateway/Builder/DataContext.cs b/Yi.Framework.Net6/Yi.Framework.OcelotGateway/Builder/DataContext.cs new file mode 100644 index 00000000..dae008e7 --- /dev/null +++ b/Yi.Framework.Net6/Yi.Framework.OcelotGateway/Builder/DataContext.cs @@ -0,0 +1,43 @@ +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using Yi.Framework.Common.Models; +using Yi.Framework.Core; + +namespace Yi.Framework.OcelotGateway.Builder +{ + public class DataContext + { + //访问路径 + public string? Path { get; set; } + + //是否为用于刷新的token + public bool? IsRe { get; set; } = false; + + //刷新令牌的路径 + public string? RefreshPath { get; set; } + + //用户白名单 + public List? UserWhitePathList { get; set; } + + //白名单路径 + public List? WhitePathList { get; set; } + + //直接放行但是需要鉴权 + public List? AccountPathList { get; set; } + + /// + /// 租户白名单 + /// + public List? TenantPathList { get; set; } + + //public UserRoleMenuEntity? UserRoleMenuEntity { get; set; } + + //最终的结果 + public Result Result { get; set; } = Result.UnAuthorize(); + + public HttpContext? Context { get; set; } + + public CacheClientDB? DB { get; set; } + + } +} diff --git a/Yi.Framework.Net6/Yi.Framework.OcelotGateway/Builder/GateStartBuilder.cs b/Yi.Framework.Net6/Yi.Framework.OcelotGateway/Builder/GateStartBuilder.cs new file mode 100644 index 00000000..f2d419e4 --- /dev/null +++ b/Yi.Framework.Net6/Yi.Framework.OcelotGateway/Builder/GateStartBuilder.cs @@ -0,0 +1,43 @@ +using System.Linq; +using System.Text; + +namespace Yi.Framework.OcelotGateway.Builder +{ + public static class GateStartBuilder + { + public static void Run(DataContext dataContext) + { + Handler(dataContext); + //基础 + AbstractBuilder whitelistBuilder = new WhiteListBuilder(); + AbstractBuilder tokenBuilder = new TokenBuilder(); + AbstractBuilder refreshBuilder = new RefreshBuilder(); + AbstractBuilder accoutBuilder = new AccoutBuilder(); + + //额外 + AbstractBuilder tenantBuilder = new TenantBuilder(); + AbstractBuilder userWhitelist = new UserWhitelistBuilder(); + + //最终 + AbstractBuilder menuBuilder = new MenuBuilder(); + + + whitelistBuilder.SetNext(tokenBuilder); + tokenBuilder.SetNext(refreshBuilder); + refreshBuilder.SetNext(accoutBuilder); + accoutBuilder.SetNext(tenantBuilder); + tenantBuilder.SetNext(userWhitelist); + userWhitelist.SetNext(menuBuilder); + whitelistBuilder.Invoke(dataContext); + } + + public static void Handler(DataContext dataContext) + { + dataContext.Path = dataContext.Path!.ToUpper(); + dataContext.RefreshPath = dataContext.RefreshPath!.ToUpper(); + dataContext.WhitePathList = dataContext.WhitePathList!.Select(white => white.ToUpper()).ToList(); + dataContext.AccountPathList = dataContext.AccountPathList!.Select(white => white.ToUpper()).ToList(); + dataContext.TenantPathList = dataContext.TenantPathList!.Select(white => white.ToUpper()).ToList(); + } + } +} diff --git a/Yi.Framework.Net6/Yi.Framework.OcelotGateway/Builder/MenuBuilder.cs b/Yi.Framework.Net6/Yi.Framework.OcelotGateway/Builder/MenuBuilder.cs new file mode 100644 index 00000000..0e60feeb --- /dev/null +++ b/Yi.Framework.Net6/Yi.Framework.OcelotGateway/Builder/MenuBuilder.cs @@ -0,0 +1,30 @@ +using Yi.Framework.Common.Models; + +namespace Yi.Framework.OcelotGateway.Builder +{ + public class MenuBuilder : AbstractBuilder + { + public override void Invoke(DataContext data) + { + //var redisData = data!.DB!.Get(RedisConst.GetStr(RedisConst.UserRoleMenu, data.UserRoleMenuEntity!.user.Account)); + //if (redisData.IsNotNull()) + //{ + // var menus = redisData.menus; + // if (menus.Where(u=> u.TypeCode == (short)MenuTypeEnum.Hide).Select(u => u.UrlControl.ToUpper()).Contains(data.Path)) + // { + + // data.Result = Result.Success(); + // } + // else + // { + // data.Result = Result.SuccessError("当前令牌无接口权限"); + // } + //} + //else + //{ + // data.Result = Result.UnAuthorize("用户信息已经过期"); + //} + + } + } +} diff --git a/Yi.Framework.Net6/Yi.Framework.OcelotGateway/Builder/RefreshBuilder.cs b/Yi.Framework.Net6/Yi.Framework.OcelotGateway/Builder/RefreshBuilder.cs new file mode 100644 index 00000000..1afd822e --- /dev/null +++ b/Yi.Framework.Net6/Yi.Framework.OcelotGateway/Builder/RefreshBuilder.cs @@ -0,0 +1,26 @@ + +using Yi.Framework.Common.Models; + +namespace Yi.Framework.OcelotGateway.Builder +{ + public class RefreshBuilder : AbstractBuilder + { + public override void Invoke(DataContext data) + { + //如果是刷新令牌 + if ((bool)data!.IsRe!) + { + //且访问路径还是正确的 + if (data.Path == data.RefreshPath) + { + data.Result = Result.Success(); + } + } + else//表示不是刷新的token,就要去redis里面判断了 + { + + base.Next(data); + } + } + } +} diff --git a/Yi.Framework.Net6/Yi.Framework.OcelotGateway/Builder/TenantBuilder.cs b/Yi.Framework.Net6/Yi.Framework.OcelotGateway/Builder/TenantBuilder.cs new file mode 100644 index 00000000..a8c1641e --- /dev/null +++ b/Yi.Framework.Net6/Yi.Framework.OcelotGateway/Builder/TenantBuilder.cs @@ -0,0 +1,22 @@ + +using Yi.Framework.Common.Models; + +namespace Yi.Framework.OcelotGateway.Builder +{ + public class TenantBuilder : AbstractBuilder + { + public override void Invoke(DataContext data) + { + + if (data!.TenantPathList!.Contains(""/*data.UserRoleMenuEntity!.tenant.TenantName*/)) + { + data.Result = Result.Success(); + } + else + { + base.Next(data); + } + + } + } +} diff --git a/Yi.Framework.Net6/Yi.Framework.OcelotGateway/Builder/TokenBuilder.cs b/Yi.Framework.Net6/Yi.Framework.OcelotGateway/Builder/TokenBuilder.cs new file mode 100644 index 00000000..55cdb874 --- /dev/null +++ b/Yi.Framework.Net6/Yi.Framework.OcelotGateway/Builder/TokenBuilder.cs @@ -0,0 +1,42 @@ + +namespace Yi.Framework.OcelotGateway.Builder +{ + public class TokenBuilder : AbstractBuilder + { + public override void Invoke(DataContext data) + { + //先鉴权 + //var userRoleMenuEntity = data!.Context.GetCurrentUserInfo(); + + + + + ////鉴权失败表示没有带token + //if (userRoleMenuEntity.IsNull()) + //{ + // //访问的路径是刷新令牌的,失败了直接返回令牌刷新失败 + // if (data.Path == data.RefreshPath) + // { + // data.Result = Result.Expire(ResultCode.RefreshTokenExpire); + // } + + //} + //else//鉴权成功,访问含有token + //{ + // //将数据存入上下文对象中 + // data.UserRoleMenuEntity = userRoleMenuEntity; + // if (userRoleMenuEntity.RefreshToken == "true") + // { + // data.IsRe = true; + // } + // data.Context!.Request.Headers.Add("Account", userRoleMenuEntity.user.Account); + // data.Context!.Request.Headers.Add("Id", userRoleMenuEntity.user.Id.ToString()); + // data.Context!.Request.Headers.Add("Name", userRoleMenuEntity.user.Name); + // data.Context!.Request.Headers.Add("TenantId", userRoleMenuEntity.user.TenantId.ToString()); + // data.Context!.Request.Headers.Add("TenantLevel", userRoleMenuEntity.tenant.TenantLevel.ToString()); + base.Next(data); + + //} + } + } +} diff --git a/Yi.Framework.Net6/Yi.Framework.OcelotGateway/Builder/UserWhiteListBuilder.cs b/Yi.Framework.Net6/Yi.Framework.OcelotGateway/Builder/UserWhiteListBuilder.cs new file mode 100644 index 00000000..d992f23f --- /dev/null +++ b/Yi.Framework.Net6/Yi.Framework.OcelotGateway/Builder/UserWhiteListBuilder.cs @@ -0,0 +1,18 @@ + +namespace Yi.Framework.OcelotGateway.Builder +{ + public class UserWhitelistBuilder : AbstractBuilder + { + public override void Invoke(DataContext data) + { + //if (data!.UserWhitePathList!.Contains(data.UserRoleMenuEntity!.user.Account)) + //{ + // data.Result = Result.Success(); + //} + //else + { + base.Next(data); + } + } + } +} diff --git a/Yi.Framework.Net6/Yi.Framework.OcelotGateway/Builder/WhiteListBuilder.cs b/Yi.Framework.Net6/Yi.Framework.OcelotGateway/Builder/WhiteListBuilder.cs new file mode 100644 index 00000000..8b270e1f --- /dev/null +++ b/Yi.Framework.Net6/Yi.Framework.OcelotGateway/Builder/WhiteListBuilder.cs @@ -0,0 +1,29 @@ + +using Yi.Framework.Common.Models; + +namespace Yi.Framework.OcelotGateway.Builder +{ + public class WhiteListBuilder : AbstractBuilder + { + public override void Invoke(DataContext data) + { + //如果在白名单,直接通行 + if (data!.WhitePathList!.Contains(data.Path!)) + { + + data.Result = Result.Success(); + } + //访问的是swagger + else if (data.Path!.Split("/")[1].ToUpper() == "swagger".ToUpper()) + { + data.Result = Result.Success(); + } + else//否则进入下一个管道处理 + { + + base.Next(data); + } + + } + } +} diff --git a/Yi.Framework.Net6/Yi.Framework.OcelotGateway/Log4net.config b/Yi.Framework.Net6/Yi.Framework.OcelotGateway/Config/Log4net.config similarity index 100% rename from Yi.Framework.Net6/Yi.Framework.OcelotGateway/Log4net.config rename to Yi.Framework.Net6/Yi.Framework.OcelotGateway/Config/Log4net.config diff --git a/Yi.Framework.Net6/Yi.Framework.OcelotGateway/Config/SwaggerDoc.xml b/Yi.Framework.Net6/Yi.Framework.OcelotGateway/Config/SwaggerDoc.xml new file mode 100644 index 00000000..35176192 --- /dev/null +++ b/Yi.Framework.Net6/Yi.Framework.OcelotGateway/Config/SwaggerDoc.xml @@ -0,0 +1,13 @@ + + + + Yi.Framework.OcelotGateway + + + + + 租户白名单 + + + + diff --git a/Yi.Framework.Net6/Yi.Framework.OcelotGateway/WebCore/OcelotExtension.cs b/Yi.Framework.Net6/Yi.Framework.OcelotGateway/WebCore/OcelotExtension.cs new file mode 100644 index 00000000..cc31ca71 --- /dev/null +++ b/Yi.Framework.Net6/Yi.Framework.OcelotGateway/WebCore/OcelotExtension.cs @@ -0,0 +1,65 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using System.Threading.Tasks; +using Yi.Framework.Common.IOCOptions; +using Yi.Framework.Core; +using Yi.Framework.OcelotGateway.Builder; +using Yi.Framework.WebCore; + +namespace Yi.Framework.OcelotGateway.WebCore +{ + public class OcelotMiddleware + { + private readonly RequestDelegate next; + private CacheClientDB _cacheClientDB; + public OcelotMiddleware(RequestDelegate next, CacheClientDB cacheClientDB) + { + this.next = next; + this._cacheClientDB = cacheClientDB; + + } + public async Task Invoke(HttpContext context) + { + //--------------------------------------访问路径-------------------------------------------- + var path = context.Request.Path.Value!; + var authorizationOptions= Appsettings.app("AuthorizationOptions"); + //-------------------------------------刷新令牌路径----------------------------------------------- + string refresh = authorizationOptions.Refresh; + //-------------------------------------白名单------------------------------------------------ + List whiteList = authorizationOptions.WhiteList; + //------------------------------------白名单需鉴权------------------------------------------ + List accountList = authorizationOptions.AccountList; + //------------------------------------用户白名单------------------------------------------ + List userList = authorizationOptions.UserList; + //------------------------------------租户白名单------------------------------------------ + List tenantList = authorizationOptions.TenantList; + + + //--------------------------------------开始组装管道--------------------------------------------- + DataContext dataContext = new() {TenantPathList= tenantList, Context = context,UserWhitePathList=userList, AccountPathList = accountList, WhitePathList = whiteList, RefreshPath = refresh, Path = path, DB = _cacheClientDB }; + //--------------------------------------管道执行--------------------------------------------- + GateStartBuilder.Run(dataContext); + //--------------------------------------处理结果--------------------------------------------- + if (dataContext.Result.status) + { + //--------------------------------------中间件执行--------------------------------------------- + await next(context); + } + else + { + context.Response.ContentType = "application/json;charset=utf-8"; + await context.Response.WriteAsync(Common.Helper.JsonHelper.ObjToStr(dataContext.Result)); + } + } + + } + + public static class OcelotExtensions + { + public static IApplicationBuilder UseOcelotExtensionService(this IApplicationBuilder builder) + { + return builder.UseMiddleware(); + } + } +} diff --git a/Yi.Framework.Net6/Yi.Framework.OcelotGateway/Yi.Framework.OcelotGateway.csproj b/Yi.Framework.Net6/Yi.Framework.OcelotGateway/Yi.Framework.OcelotGateway.csproj index 6856e024..3ddebcc9 100644 --- a/Yi.Framework.Net6/Yi.Framework.OcelotGateway/Yi.Framework.OcelotGateway.csproj +++ b/Yi.Framework.Net6/Yi.Framework.OcelotGateway/Yi.Framework.OcelotGateway.csproj @@ -1,11 +1,12 @@ - + net6.0 + enable - D:\CC.Yi\CC.Yi\Yi.Framework.Net6\Yi.Framework.OcelotGateway\SwaggerDoc.xml + ./Config/SwaggerDoc.xml 1701;1702;CS1591 diff --git a/Yi.Framework.Net6/Yi.Framework.Repository/DataContext.cs b/Yi.Framework.Net6/Yi.Framework.Repository/DataContext.cs new file mode 100644 index 00000000..ba952c26 --- /dev/null +++ b/Yi.Framework.Net6/Yi.Framework.Repository/DataContext.cs @@ -0,0 +1,70 @@ +using SqlSugar; + +namespace Yi.Framework.Repository +{ + public class DataContext : SimpleClient where T : class, new() + { + public DataContext(ISqlSugarClient context = null!) : base(context) + { + if (context == null) + { + base.Context = Db; + } + } + /// + /// SqlSugarScope操作数据库是线程安的可以单例 + /// + public static SqlSugarScope Db = new SqlSugarScope(new ConnectionConfig() + { + DbType = SqlSugar.DbType.MySql, + //ConnectionString = Appsettings.app("ConnectionStrings","mysqlConnection") , + IsAutoCloseConnection = true + }, + db => + { + + db.Aop.DataExecuting = (oldValue, entityInfo) => + { + //var httpcontext = ServiceLocator.Instance.GetService().HttpContext; + switch (entityInfo.OperationType) + { + case DataFilterType.InsertByObject: + if (entityInfo.PropertyName == "CreateUser") + { + //entityInfo.SetValue(new Guid(httpcontext.Request.Headers["Id"].ToString())); + } + + if (entityInfo.PropertyName == "TenantId") + { + //现在不能直接给了,要根据判断一下租户等级,如果租户等级是1,不给,需要自己去赋值,如果租户等级是0,就执行下面的。 + //entityInfo.SetValue(new Guid(httpcontext.Request.Headers["TenantId"].ToString())); + //查询的时候,也需要判断一下,如果是租户等级,不要租户条件,如果是超级租户,就返回所有 + } + break; + case DataFilterType.UpdateByObject: + if (entityInfo.PropertyName == "ModifyTime") + { + entityInfo.SetValue(DateTime.Now); + } + if (entityInfo.PropertyName == "ModifyUser") + { + //entityInfo.SetValue(new Guid(httpcontext.Request.Headers["Id"].ToString())); + } + break; + } + //inset生效 + + }; + //如果用单例配置要统一写在这儿 + db.Aop.OnLogExecuting = (s, p) => + { + + Console.WriteLine("_______________________________________________"); + Console.WriteLine(s); + }; + + }); + + + } +} diff --git a/Yi.Framework.Net6/Yi.Framework.Repository/IRepository.cs b/Yi.Framework.Net6/Yi.Framework.Repository/IRepository.cs new file mode 100644 index 00000000..6efecffd --- /dev/null +++ b/Yi.Framework.Net6/Yi.Framework.Repository/IRepository.cs @@ -0,0 +1,31 @@ +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Text; +using System.Threading.Tasks; + +namespace Yi.Framework.Repository +{ + public interface IRepository : ISimpleClient where T : class, new() + { + public Task InsertReturnEntityAsync(T entity); + public object CommonPage(QueryParameters pars, int pageIndex, int pageSize); + public object CommonPage(QueryParameters pars, int pageIndex, int pageSize, bool whereBool, Expression> where); + + public object CommonPageMapper(Expression> expression, QueryParameters pars, int pageIndex, int pageSize, bool whereBool, Expression> where); + + public Task FirstMapperAsync(Expression> expression, bool isTenant = true); + + public Task> ToListMapperAsync(Expression> expression, bool isTenant = true); + + public Task> ToListMapperAsync(Expression> expression, bool whereBool, Expression> where, bool isTenant = true); + + public Task> GetListAsync(Expression> whereExpression, bool whereBool, Expression> where, bool isTenant = true); + + public Task> GetListAsync(bool whereBool, Expression> where, bool isTenant = true); + public Task> StoreAsync(string storeName, object para); + + } +} diff --git a/Yi.Framework.Net6/Yi.Framework.Repository/Repository.cs b/Yi.Framework.Net6/Yi.Framework.Repository/Repository.cs new file mode 100644 index 00000000..f3ceccf9 --- /dev/null +++ b/Yi.Framework.Net6/Yi.Framework.Repository/Repository.cs @@ -0,0 +1,321 @@ +using SqlSugar; +using System.Data; +using System.Linq.Expressions; +using static Yi.Framework.Repository.QueryParametersExtensions; + +/***这里面写的代码不会给覆盖,如果要重新生成请删除 Repository.cs ***/ +namespace Yi.Framework.Repository +{ + /// + /// 仓储模式 + /// + /// + public class Repository : DataContext ,IRepository where T : class, new() + { + + /// + /// 构造函数 + /// + /// + public Repository(ISqlSugarClient context = null) : base(context)//注意这里要有默认值等于null + { + if (context == null) + { + base.Context = Db; + } + } + + + + public async Task InsertReturnEntityAsync(T entity) + { + return await Db.Insertable(entity).ExecuteReturnEntityAsync(); + } + /// + /// whereif与where混搭,多租户 + /// + /// + /// + /// + /// + public async Task> GetListAsync(Expression> whereExpression, bool whereBool, Expression> where, bool isTenant = true) + { + return await Db.Queryable().WhereIF(whereBool, where).Where(whereExpression).WhereTenant(isTenant).ToListAsync(); + } + + /// + /// where重载,多租户 + /// + /// + /// + /// + public async Task> GetListAsync(bool whereBool, Expression> where, bool isTenant = true) + { + return await Db.Queryable().WhereIF(whereBool, where).WhereTenant(isTenant). ToListAsync(); + } + + + + /// + /// 左连接,三表连接,返回最右边的列表,多租户 + /// + /// + /// + /// + /// + /// + /// + /// + public async Task> LeftJoinListAsync(Expression> joinQueryable1, Expression> joinQueryable12, Expression> whereLambda, Expression> selectLambda, bool isTenant = true) + { + return await Db.Queryable().LeftJoin(joinQueryable1) + .LeftJoin(joinQueryable12) + .Where(whereLambda) + .WhereTenant(isTenant) + .Select(selectLambda) + .ToListAsync(); + } + + public async Task> StoreAsync(string storeName, object para) + { + return await Db.Ado.UseStoredProcedure().SqlQueryAsync(storeName, para); + } + + /// + /// 调用sql + /// + /// + /// + /// + public async Task SqlDataTableAsync(string sql, object para = null) + { + return await Db.Ado.GetDataTableAsync(sql, para); + } + + /// + /// 导航属性mapper返回一个,多租户 + /// + /// + /// + /// + /// + public async Task FirstMapperAsync(Expression> expression,bool isTenant=true) + { + return await Db.Queryable().Mapper(expression).WhereTenant(isTenant).FirstAsync(); + } + + /// + /// 导航属性mapper返回一组,多租户 + /// + /// + /// + /// + /// + public async Task> ToListMapperAsync(Expression> expression, bool isTenant = true) + { + return await Db.Queryable() .Mapper(expression).WhereTenant(isTenant).ToListAsync(); + } + + + + + /// + /// 导航属性mapper返回一组.同时添加条件,多租户 + /// + /// + /// + /// + /// + /// + public async Task> ToListMapperAsync(Expression> expression, bool whereBool, Expression> where, bool isTenant = true) + { + return await Db.Queryable().Mapper(expression).WhereIF(whereBool,where).WhereTenant(isTenant).ToListAsync(); + } + + + /// + /// 仓储扩展方法:单表查询通用分页 + /// + /// + public object CommonPage(QueryParameters pars, int pageIndex, int pageSize) + { + int tolCount = 0; + var sugarParamters = pars.Parameters.Select(it => (IConditionalModel)new ConditionalModel() + { + ConditionalType = it.ConditionalType, + FieldName = it.FieldName, + FieldValue = it.FieldValue + }).ToList(); + var query = Db.Queryable(); + if (pars.OrderBys != null) + { + foreach (var item in pars.OrderBys) + { + query.OrderBy(item.ToSqlFilter());//格式 id asc或者 id desc + } + } + var result = query.Where(sugarParamters).ToPageList(pageIndex, pageSize, ref tolCount); + return new + { + count = tolCount, + data = result + }; + } + + + /// + /// 额外添加动态条件拼接 + /// + /// + public object CommonPage(QueryParameters pars, int pageIndex, int pageSize, bool whereBool, Expression> where) + { + int tolCount = 0; + var sugarParamters = pars.Parameters.Select(it => (IConditionalModel)new ConditionalModel() + { + ConditionalType = it.ConditionalType, + FieldName = it.FieldName, + FieldValue = it.FieldValue + }).ToList(); + var query = Db.Queryable(); + if (pars.OrderBys != null) + { + foreach (var item in pars.OrderBys) + { + query.OrderBy(item.ToSqlFilter());//格式 id asc或者 id desc + } + } + var result = query.WhereIF(whereBool, where).Where(sugarParamters).ToPageList(pageIndex, pageSize, ref tolCount); + return new + { + count = tolCount, + data = result + }; + } + + + + /// + /// 导航属性mapper分页多条件 + /// + /// + /// + /// + /// + public object CommonPageMapper(Expression> expression, QueryParameters pars, int pageIndex, int pageSize,bool whereBool, Expression> where) + { + int tolCount = 0; + var sugarParamters = pars.Parameters.Select(it => (IConditionalModel)new ConditionalModel() + { + ConditionalType = it.ConditionalType, + FieldName = it.FieldName, + FieldValue = it.FieldValue + }).ToList(); + var query = Db.Queryable(); + if (pars.OrderBys != null) + { + foreach (var item in pars.OrderBys) + { + query.OrderBy(item.ToSqlFilter());//格式 id asc或者 id desc + } + } + var result = query.Mapper < T, T2, TT>(expression).WhereIF(whereBool, where). Where(sugarParamters).ToPageList(pageIndex, pageSize, ref tolCount); + return new + { + count = tolCount, + data = result + }; + } + + } + + /// + /// 通用查询参数 + /// + public class QueryParameters + { + public List Parameters { get; set; } = new List(); + public List OrderBys { get; set; } = new List(); + } + + public static class QueryParametersExtensions + { + + public static ISugarQueryable WhereTenant(this ISugarQueryable db, bool isTenant = true) + { + if (isTenant) + { + var sugarParamters = new QueryParameters().SetParameters(new Dictionary()).Parameters.Select(it => (IConditionalModel)new ConditionalModel() + { + ConditionalType = it.ConditionalType, + FieldName = it.FieldName, + FieldValue = it.FieldValue + }).ToList(); + return db.Where(sugarParamters); + } + + + return db; + + } + public static ISugarQueryable WhereTenant(this ISugarQueryable db, bool isTenant = true) + { + if (isTenant) + { + var sugarParamters = new QueryParameters().SetParameters(new Dictionary()).Parameters.Select(it => (IConditionalModel)new ConditionalModel() + { + ConditionalType = it.ConditionalType, + FieldName = it.FieldName, + FieldValue = it.FieldValue + }).ToList(); + return db.Where(sugarParamters); + } + + return db; + + + } + + public static QueryParameters SetParameters(this QueryParameters queryParameters, Dictionary dic,bool IsTenant=true) + { + //var httpcontext = ServiceLocator.Instance.GetService().HttpContext; + queryParameters.OrderBys = new List { "CreateTime" }; + + + foreach (var p in dic) + { + QueryParameter qp = null; + if (p.Key == "IsDeleted" || p.Key=="Id") + { + qp= new QueryParameter() { FieldName = p.Key, FieldValue = p.Value, ConditionalType = ConditionalType.Equal }; + + } + else + { + qp= new QueryParameter() { FieldName = p.Key, FieldValue = p.Value }; + + } + queryParameters.Parameters.Add(qp); + } + if (IsTenant) + { + //if (httpcontext.Request.Headers["TenantLevel"].ToString() == "0") + //{ + // queryParameters.Parameters.Add(new QueryParameter() { ConditionalType = ConditionalType.Equal, FieldName = "TenantId", FieldValue = httpcontext.Request.Headers["TenantId"].ToString() }); + //} + } + + return queryParameters; + } + + /// + /// 通用查询参数 + /// + public class QueryParameter + { + public string FieldName { get; set; } + public string FieldValue { get; set; } + public ConditionalType ConditionalType { get; set; } = ConditionalType.Like; + + } + } +} \ No newline at end of file diff --git a/Yi.Framework.Net6/Yi.Framework.Repository/Yi.Framework.Repository.csproj b/Yi.Framework.Net6/Yi.Framework.Repository/Yi.Framework.Repository.csproj new file mode 100644 index 00000000..01a60d35 --- /dev/null +++ b/Yi.Framework.Net6/Yi.Framework.Repository/Yi.Framework.Repository.csproj @@ -0,0 +1,13 @@ + + + + net6.0 + enable + disable + + + + + + + diff --git a/Yi.Framework.Net6/Yi.Framework.Service/BaseService.cs b/Yi.Framework.Net6/Yi.Framework.Service/BaseService.cs deleted file mode 100644 index c74a9760..00000000 --- a/Yi.Framework.Net6/Yi.Framework.Service/BaseService.cs +++ /dev/null @@ -1,136 +0,0 @@ -using Microsoft.EntityFrameworkCore; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Text; -using System.Threading.Tasks; -using Yi.Framework.Common.Enum; -using Yi.Framework.Interface; -using Yi.Framework.Model.ModelFactory; - -namespace Yi.Framework.Service -{ - public class BaseService : IBaseService where T : class, new() - { - public DbContext _Db; - public DbContext _DbRead; - public IDbContextFactory _DbFactory; - public BaseService(IDbContextFactory DbFactory) - { - _DbFactory = DbFactory; - _Db = DbFactory.ConnWriteOrRead(WriteAndReadEnum.Write); - _DbRead = DbFactory.ConnWriteOrRead(WriteAndReadEnum.Read); - } - - public async Task GetEntityById(int id) - { - return await _Db.Set().FindAsync(id); - } - - - public async Task> GetAllEntitiesAsync() - { - return await _Db.Set().ToListAsync(); - } - - public async Task> GetEntitiesAsync(Expression> whereLambda) - { - return await _Db.Set().Where(whereLambda).ToListAsync(); - } - - public async Task GetCountAsync(Expression> whereLambda) //统计数量 - { - return await _Db.Set().CountAsync(whereLambda); - } - - public IQueryable> GetGroup(Expression> whereLambda, Expression> groupByLambda) //分组 - { - return _Db.Set().Where(whereLambda).GroupBy(groupByLambda).AsQueryable(); - } - - public async Task, int>> GetPageEntities(int pageSize, int pageIndex, Expression> whereLambda, Expression> orderByLambda, bool isAsc) - { - int total = await GetCountAsync(whereLambda); - - IEnumerable pageData; - if (isAsc) - { - pageData = await _Db.Set().Where(whereLambda) - .OrderBy(orderByLambda) - .Skip(pageSize * (pageIndex - 1)) - .Take(pageSize).ToListAsync(); - } - else - { - pageData = await _Db.Set().Where(whereLambda) - .OrderByDescending(orderByLambda) - .Skip(pageSize * (pageIndex - 1)) - .Take(pageSize).ToListAsync(); - } - - return Tuple.Create, int>(pageData, total); - } - - public async Task AddAsync(T entity) - { - _Db.Set().Add(entity); - return await _Db.SaveChangesAsync() > 0; - } - - public async Task AddAsync(IEnumerable entities) - { - _Db.Set().AddRange(entities); - return await _Db.SaveChangesAsync() > 0; - } - - public async Task UpdateAsync(T entity) - { - _Db.Set().Update(entity); - return await _Db.SaveChangesAsync() > 0; - } - - public async Task UpdateListAsync(IEnumerable entities) - { - _Db.Set().UpdateRange(entities); - return await _Db.SaveChangesAsync() > 0; - } - - public async Task DeleteAsync(T entity) - { - _Db.Set().Remove(entity); - return await _Db.SaveChangesAsync() > 0; - } - - public async Task DeleteAsync(int id) - { - _Db.Set().Remove(await GetEntityById(id)); - return await _Db.SaveChangesAsync() > 0; - } - - public async Task DeleteAsync(IEnumerable ids) - { - foreach (var id in ids) - { - _Db.Set().RemoveRange(await GetEntityById(id)); - } - return await _Db.SaveChangesAsync() > 0; - } - public async Task DeleteAsync(Expression> where) - { - IEnumerable entities = await GetEntitiesAsync(where); - if (entities != null) - { - _Db.Set().RemoveRange(entities); - - return await _Db.SaveChangesAsync() > 0; - } - return false; - } - - public async Task GetEntity(Expression> whereLambda) - { - return await _Db.Set().Where(whereLambda).FirstOrDefaultAsync(); - } - } -} diff --git a/Yi.Framework.Net6/Yi.Framework.Service/MenuService.cs b/Yi.Framework.Net6/Yi.Framework.Service/MenuService.cs deleted file mode 100644 index 5e05dc93..00000000 --- a/Yi.Framework.Net6/Yi.Framework.Service/MenuService.cs +++ /dev/null @@ -1,72 +0,0 @@ -using Microsoft.EntityFrameworkCore; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Yi.Framework.Common.Enum; -using Yi.Framework.Common.Helper; -using Yi.Framework.Core; -using Yi.Framework.Interface; -using Yi.Framework.Model.Models; - -namespace Yi.Framework.Service -{ - public partial class MenuService:BaseService, IMenuService - { - short Normal = (short)DelFlagEnum.Normal; - public async Task AddChildrenMenu(int menu_id, menu _children) - { - _children.parentId = menu_id; - _children.is_top = (short)TopFlagEnum.Children; - _children.is_delete = (short)DelFlagEnum.Normal; - await AddAsync(_children); - return _children; - } - - public async Task AddTopMenu(menu _menu) - { - _menu.is_top = (short)TopFlagEnum.Children; - - return await AddAsync(_menu); - } - - public async Task GetMenuInMould() - { - var menu_data = await _DbRead.Set().Include(u => u.mould).Where(u=>u.is_delete==(short)DelFlagEnum.Normal).ToListAsync(); - return TreeHelper.SetTree(menu_data, null)[0]; ; - } - - - public async Task> GetTopMenusByTopMenuIds(List menuIds) - { - return await _DbRead.Set().AsNoTracking().Where(u => menuIds.Contains(u.id)).OrderBy(u=>u.sort).ToListAsync(); - } - - public async Task SetMouldByMenu(int id1,int id2) - { - var menu_data = await _DbRead.Set().Include(u => u.mould).Where(u => u.id == id1).FirstOrDefaultAsync(); - var mould_data = await _DbRead.Set().Where(u => u.id == id1).FirstOrDefaultAsync(); - menu_data.mould = mould_data; - _Db.Update(menu_data); - return menu_data; - } - - - public async Task> GetTopMenuByUserId(int userId) - { - var user_data = await _DbRead.Set().Include(u => u.roles).ThenInclude(u => u.menus).Where(u=>u.id==userId).FirstOrDefaultAsync(); - List menuList = new(); - user_data.roles.ForEach(u => - { - var m = u.menus.Where(u => u.is_delete == Normal).ToList(); - menuList = menuList.Union(m).ToList(); - }); - - var menuIds=menuList.Select(u => u.id).ToList(); - - return await _DbRead.Set().Include(u => u.mould).Where(u => menuIds.Contains(u.id)).ToListAsync(); - } - - } -} diff --git a/Yi.Framework.Net6/Yi.Framework.Service/MouldService.cs b/Yi.Framework.Net6/Yi.Framework.Service/MouldService.cs deleted file mode 100644 index 21409683..00000000 --- a/Yi.Framework.Net6/Yi.Framework.Service/MouldService.cs +++ /dev/null @@ -1,25 +0,0 @@ -using Microsoft.EntityFrameworkCore; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Yi.Framework.Interface; -using Yi.Framework.Model.Models; - -namespace Yi.Framework.Service -{ - public partial class MouldService:BaseService, IMouldService - { - /// - /// 这个获取的是菜单,用的是菜单表,应该放到菜单service里面,像这种只用到id的,就传一个id就可以了 - /// - /// - /// - public async Task GetMenuByMould(mould _mould) - { - var menu_data = await _Db.Set().Include(u => u.mould).Where(u => u.mould == _mould && u.is_delete == (short)Common.Enum.DelFlagEnum.Normal).FirstOrDefaultAsync(); - return menu_data; - } - } -} diff --git a/Yi.Framework.Net6/Yi.Framework.Service/RoleService.cs b/Yi.Framework.Net6/Yi.Framework.Service/RoleService.cs deleted file mode 100644 index d604ea26..00000000 --- a/Yi.Framework.Net6/Yi.Framework.Service/RoleService.cs +++ /dev/null @@ -1,65 +0,0 @@ -using Microsoft.EntityFrameworkCore; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Yi.Framework.Interface; -using Yi.Framework.Model.Models; - -namespace Yi.Framework.Service -{ - public partial class RoleService : BaseService, IRoleService - { - short Normal = (short)Common.Enum.DelFlagEnum.Normal; - - public async Task> GetRolesByUserId(int userId) - { - var user_data = await _Db.Set().Include(u => u.roles).Where(u => u.id == userId).FirstOrDefaultAsync(); - var roleList = user_data.roles.Where(u => u.is_delete == Normal).ToList(); - roleList.ForEach(u => u.users = null); - return roleList; - } - - - public async Task SetMenusByRolesId(List menuIds, List roleIds) - { - var role_data = await _Db.Set().Include(u => u.menus).Where(u => roleIds.Contains(u.id) && u.is_delete == Normal).ToListAsync(); - var menuList = await _Db.Set().Where(u => menuIds.Contains(u.id) && u.is_delete == Normal).ToListAsync(); - foreach (var role in role_data) - { - role.menus = menuList; - } - return await UpdateListAsync(role_data); - } - - public async Task> GetMenusByRoleId(List roleIds) - { - var role_data = await _Db.Set().Include(u => u.menus).Where(u => roleIds.Contains(u.id) && u.is_delete == Normal).ToListAsync(); - List menuList = new(); - role_data.ForEach(u => - { - var m = u.menus.Where(u => u.is_delete == Normal).ToList(); - menuList = menuList.Union(m).ToList(); - }); - return menuList; - } - public async Task> GetTopMenusByRoleId(int roleId) - { - var role_data = await _Db.Set().Include(u => u.menus).Where(u => u.id == roleId).FirstOrDefaultAsync(); - var menuList = role_data.menus.Where(u => u.is_delete == Normal).ToList(); - - menuList.ForEach(u => u.roles = null); - - return menuList; - } - - public async Task> GetMenusByRole(int roleId) - { - var role_data = await _Db.Set().Include(u => u.menus).Where(u => u.id == roleId).FirstOrDefaultAsync(); - var menuList = role_data.menus.Where(u => u.is_delete == Normal).ToList(); - return menuList; - } - - } -} diff --git a/Yi.Framework.Net6/Yi.Framework.Service/T4Service.cs b/Yi.Framework.Net6/Yi.Framework.Service/T4Service.cs deleted file mode 100644 index 1b59d0eb..00000000 --- a/Yi.Framework.Net6/Yi.Framework.Service/T4Service.cs +++ /dev/null @@ -1,103 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Yi.Framework.Model.Models; -using Yi.Framework.Interface; -using Microsoft.EntityFrameworkCore; -using Yi.Framework.Model.ModelFactory; - -namespace Yi.Framework.Service -{ - - public partial class MenuService:BaseService,IMenuService - { - public MenuService(IDbContextFactory DbFactory):base(DbFactory){ } - - public async Task DelListByUpdateAsync(List _ids) - { - var menuList = await GetEntitiesAsync(u=>_ids.Contains(u.id)); - menuList.ToList().ForEach(u => u.is_delete = (short)Common.Enum.DelFlagEnum.Deleted); - return await UpdateListAsync(menuList); - } - - public async Task> GetAllEntitiesTrueAsync() - { - return await GetEntitiesAsync(u=> u.is_delete == (short)Common.Enum.DelFlagEnum.Normal); - } - - } - - public partial class MouldService:BaseService,IMouldService - { - public MouldService(IDbContextFactory DbFactory):base(DbFactory){ } - - public async Task DelListByUpdateAsync(List _ids) - { - var mouldList = await GetEntitiesAsync(u=>_ids.Contains(u.id)); - mouldList.ToList().ForEach(u => u.is_delete = (short)Common.Enum.DelFlagEnum.Deleted); - return await UpdateListAsync(mouldList); - } - - public async Task> GetAllEntitiesTrueAsync() - { - return await GetEntitiesAsync(u=> u.is_delete == (short)Common.Enum.DelFlagEnum.Normal); - } - - } - - public partial class RoleService:BaseService,IRoleService - { - public RoleService(IDbContextFactory DbFactory):base(DbFactory){ } - - public async Task DelListByUpdateAsync(List _ids) - { - var roleList = await GetEntitiesAsync(u=>_ids.Contains(u.id)); - roleList.ToList().ForEach(u => u.is_delete = (short)Common.Enum.DelFlagEnum.Deleted); - return await UpdateListAsync(roleList); - } - - public async Task> GetAllEntitiesTrueAsync() - { - return await GetEntitiesAsync(u=> u.is_delete == (short)Common.Enum.DelFlagEnum.Normal); - } - - } - - public partial class UserService:BaseService,IUserService - { - public UserService(IDbContextFactory DbFactory):base(DbFactory){ } - - public async Task DelListByUpdateAsync(List _ids) - { - var userList = await GetEntitiesAsync(u=>_ids.Contains(u.id)); - userList.ToList().ForEach(u => u.is_delete = (short)Common.Enum.DelFlagEnum.Deleted); - return await UpdateListAsync(userList); - } - - public async Task> GetAllEntitiesTrueAsync() - { - return await GetEntitiesAsync(u=> u.is_delete == (short)Common.Enum.DelFlagEnum.Normal); - } - - } - - public partial class VisitService:BaseService,IVisitService - { - public VisitService(IDbContextFactory DbFactory):base(DbFactory){ } - - public async Task DelListByUpdateAsync(List _ids) - { - var visitList = await GetEntitiesAsync(u=>_ids.Contains(u.id)); - visitList.ToList().ForEach(u => u.is_delete = (short)Common.Enum.DelFlagEnum.Deleted); - return await UpdateListAsync(visitList); - } - - public async Task> GetAllEntitiesTrueAsync() - { - return await GetEntitiesAsync(u=> u.is_delete == (short)Common.Enum.DelFlagEnum.Normal); - } - - } -} diff --git a/Yi.Framework.Net6/Yi.Framework.Service/T4Service.tt b/Yi.Framework.Net6/Yi.Framework.Service/T4Service.tt deleted file mode 100644 index ba340807..00000000 --- a/Yi.Framework.Net6/Yi.Framework.Service/T4Service.tt +++ /dev/null @@ -1,58 +0,0 @@ -<#@ template debug="false" hostspecific="true" language="C#" #> -<#@ assembly name="System.Core" #> -<#@ import namespace="System.Linq" #> -<#@ import namespace="System.Text" #> -<#@ import namespace="System.IO" #> -<#@ import namespace="System.Collections.Generic" #> -<#@ output extension=".cs" #> -<# - string solutionsPath = Host.ResolveAssemblyReference("$(SolutionDir)");//获取解决方案路径 - string dirPath= Path.Combine(solutionsPath,@"Yi.Framework.Model\Models\"); - DirectoryInfo dir = new DirectoryInfo(dirPath); - FileInfo[] finfo = dir.GetFiles(); - string filenames = string.Empty; - List filenameList = new List(); - for (int i = 0; i < finfo.Length; i++) - { - filenames = finfo[i].Name ; - string[] fname=filenames.Split('.'); - filenameList.Add(fname[0]); - } - - -#> -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Yi.Framework.Model.Models; -using Yi.Framework.Interface; -using Microsoft.EntityFrameworkCore; -using Yi.Framework.Model.ModelFactory; - -namespace Yi.Framework.Service -{ - <# foreach(string k in filenameList){ - string fn= k.Substring(0,1).ToUpper()+k.Substring(1); - #> - - public partial class <#= fn #>Service:BaseService<<#= k #>>,I<#= fn #>Service - { - public <#= fn #>Service(IDbContextFactory DbFactory):base(DbFactory){ } - - public async Task DelListByUpdateAsync(List _ids) - { - var <#= k #>List = await GetEntitiesAsync(u=>_ids.Contains(u.id)); - <#= k #>List.ToList().ForEach(u => u.is_delete = (short)Common.Enum.DelFlagEnum.Deleted); - return await UpdateListAsync(<#= k #>List); - } - - public async Task>> GetAllEntitiesTrueAsync() - { - return await GetEntitiesAsync(u=> u.is_delete == (short)Common.Enum.DelFlagEnum.Normal); - } - - } -<# } #> -} diff --git a/Yi.Framework.Net6/Yi.Framework.Service/UserService.cs b/Yi.Framework.Net6/Yi.Framework.Service/UserService.cs index efb8dc39..6e87ae10 100644 --- a/Yi.Framework.Net6/Yi.Framework.Service/UserService.cs +++ b/Yi.Framework.Net6/Yi.Framework.Service/UserService.cs @@ -1,5 +1,4 @@ -using Microsoft.EntityFrameworkCore; -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; @@ -8,106 +7,15 @@ using System.Threading.Tasks; using Yi.Framework.Common.Const; using Yi.Framework.Common.Helper; using Yi.Framework.Core; -using Yi.Framework.DTOModel; using Yi.Framework.Interface; using Yi.Framework.Model; -using Yi.Framework.Model.ModelFactory; using Yi.Framework.Model.Models; +using Yi.Framework.Repository; namespace Yi.Framework.Service { - public partial class UserService : BaseService, IUserService + public partial class UserService : Repository, IUserService { - CacheClientDB _cacheClientDB; - public UserService(CacheClientDB cacheClientDB, IDbContextFactory DbFactory) : base(DbFactory) - { - _cacheClientDB = cacheClientDB; - } - short Normal = (short)Common.Enum.DelFlagEnum.Normal; - public async Task PhoneIsExsit(string smsAddress) - { - var userList = await GetEntity(u => u.phone == smsAddress); - if (userList == null) - { - return false; - } - return true; - } - - public async Task EmailIsExsit(string emailAddress) - { - var userList = await GetEntity(u => u.email == emailAddress); - if (userList == null) - { - return false; - } - return true; - } - /// - /// - /// - /// - /// - public async Task GetUserById(int userId) - { - var user_data = await _DbRead.Set().Include(u => u.roles).ThenInclude(u => u.menus).ThenInclude(u => u.mould).Where(u => u.id == userId).FirstOrDefaultAsync(); - return user_data; - - } - public async Task> GetAxiosByRouter(string router, List menuIds) - { - var menu_data= await _DbRead.Set().Where(u => u.router.Trim().ToUpper() == router.Trim().ToUpper() && u.is_delete == (short)Common.Enum.DelFlagEnum.Normal).FirstOrDefaultAsync(); - return await _DbRead.Set().Include(u=>u.mould).Where(u => u.parentId == menu_data.id && u.is_delete == (short)Common.Enum.DelFlagEnum.Normal).ToListAsync(); - } - - public async Task GetMenuByHttpUser(List allMenuIds) - { - var topMenu = await _DbRead.Set().Where(u => allMenuIds.Contains(u.id)&& u.is_show == (short)Common.Enum.ShowFlagEnum.Show && u.is_delete == (short)Common.Enum.DelFlagEnum.Normal).ToListAsync(); - //现在要开始关联菜单了 - return TreeHelper.SetTree(topMenu)[0]; - } - public async Task GetUserInRolesByHttpUser(int userId) - { - var data = await GetUserById(userId); - data.roles?.ForEach(u => - { - u.users = null; - u.menus = null; - }); - return data; - } - - public async Task Login(user _user) - { - var user_data = await _DbRead.Set().Include(u => u.roles).Where(u => u.username == _user.username && u.password == _user.password && u.is_delete == Normal).FirstOrDefaultAsync(); - return user_data; - } - - public async Task Register(user _user) - { - var user_data = await GetEntity(u => u.username == _user.username); - if (user_data != null) - { - return false; - } - return await UpdateAsync(_user); - } - - public async Task SetRoleByUser(List roleIds, List userIds) - { - var user_data = await _DbRead.Set().Include(u => u.roles).Where(u => userIds.Contains(u.id)).ToListAsync(); - var roleList = await _DbRead.Set().Where(u => roleIds.Contains(u.id)).ToListAsync(); - user_data.ForEach(u => u.roles = roleList); - return await UpdateListAsync(user_data); - } - - public bool SaveUserApi(int userId, List menus) - { - return _cacheClientDB.Set(RedisConst.userMenusApi + ":" + userId.ToString(), menus, new TimeSpan(0, 30, 0)); - } - public List GetCurrentMenuInfo(int userId) - { - return _cacheClientDB.Get>(RedisConst.userMenusApi + ":" + userId).Select(u => u.id).ToList(); - } + } } diff --git a/Yi.Framework.Net6/Yi.Framework.Service/Yi.Framework.Service.csproj b/Yi.Framework.Net6/Yi.Framework.Service/Yi.Framework.Service.csproj index 128fbe41..b2526495 100644 --- a/Yi.Framework.Net6/Yi.Framework.Service/Yi.Framework.Service.csproj +++ b/Yi.Framework.Net6/Yi.Framework.Service/Yi.Framework.Service.csproj @@ -13,25 +13,11 @@ - - - - - T4Service.cs - TextTemplatingFileGenerator - + - - - True - True - T4Service.tt - - - diff --git a/Yi.Framework.Net6/Yi.Framework.Task/VisitJob.cs b/Yi.Framework.Net6/Yi.Framework.Task/VisitJob.cs index 2c95b7cf..2dec370c 100644 --- a/Yi.Framework.Net6/Yi.Framework.Task/VisitJob.cs +++ b/Yi.Framework.Net6/Yi.Framework.Task/VisitJob.cs @@ -1,5 +1,4 @@  -using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using Quartz; using System; @@ -7,7 +6,6 @@ using System.IO; using System.Text; using System.Threading.Tasks; using Yi.Framework.Common.Models; -using Yi.Framework.Model.ModelFactory; using Yi.Framework.Model.Models; namespace Yi.Framework.Job @@ -15,11 +13,9 @@ namespace Yi.Framework.Job public class VisitJob : IJob { private ILogger _logger; - private DbContext _DBWrite; - public VisitJob(ILogger logger, IDbContextFactory DbFactory) + public VisitJob(ILogger logger) { _logger = logger; - _DBWrite = DbFactory.ConnWriteOrRead(Common.Enum.WriteAndReadEnum.Write); } /// @@ -31,8 +27,6 @@ namespace Yi.Framework.Job { return Task.Run(() => { - _DBWrite.Set().Add(new visit() { num = JobModel.visitNum, time = DateTime.Now }); - _DBWrite.SaveChanges(); _logger.LogWarning("定时任务开始调度:" + nameof(VisitJob) + ":" + DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + $":访问总数为:{JobModel.visitNum}"); JobModel.visitNum = 0; } diff --git a/Yi.Framework.Net6/Yi.Framework.WebCore/AuthorizationPolicy/CustomAuthorizationHandler.cs b/Yi.Framework.Net6/Yi.Framework.WebCore/AuthorizationPolicy/CustomAuthorizationHandler.cs index 111842ea..14e166ba 100644 --- a/Yi.Framework.Net6/Yi.Framework.WebCore/AuthorizationPolicy/CustomAuthorizationHandler.cs +++ b/Yi.Framework.Net6/Yi.Framework.WebCore/AuthorizationPolicy/CustomAuthorizationHandler.cs @@ -7,7 +7,6 @@ using System.Security.Claims; using System.Threading.Tasks; using Yi.Framework.Common.Const; using Yi.Framework.Core; -using Yi.Framework.DTOModel; using Yi.Framework.Model.Models; namespace Yi.Framework.WebCore.AuthorizationPolicy @@ -45,15 +44,15 @@ namespace Yi.Framework.WebCore.AuthorizationPolicy //现在只需要登录的时候把用户的api路径添加到redis去 //每次访问的时候进行redis判断一下即可 //注意一下,redis不能一直保存,和jwt一样搞一个期限 - var menuList=_cacheClientDB.Get>(RedisConst.userMenusApi+":"+currentUserId); - foreach (var k in menuList) - { - if (k.mould != null) - { - dicMenueDictionary.Add(k.mould?.id.ToString(), "/api"+ k.mould?.url); - } + //var menuList=_cacheClientDB.Get>(RedisConst.userMenusApi+":"+currentUserId); + //foreach (var k in menuList) + //{ + // if (k.mould != null) + // { + // dicMenueDictionary.Add(k.mould?.id.ToString(), "/api"+ k.mould?.url); + // } - } + //} if (dicMenueDictionary.ContainsValue(httpcontext.Request.Path)) { diff --git a/Yi.Framework.Net6/Yi.Framework.WebCore/CommonExtend.cs b/Yi.Framework.Net6/Yi.Framework.WebCore/CommonExtend.cs index ccdc66ac..7149ef88 100644 --- a/Yi.Framework.Net6/Yi.Framework.WebCore/CommonExtend.cs +++ b/Yi.Framework.Net6/Yi.Framework.WebCore/CommonExtend.cs @@ -30,7 +30,7 @@ namespace Yi.Framework.WebCore /// /// /// - public static user GetCurrentUserInfo(this HttpContext httpContext, out List menuIds) + public static User GetCurrentUserInfo(this HttpContext httpContext, out List menuIds) { IEnumerable claimlist = httpContext.AuthenticateAsync().Result.Principal.Claims; @@ -40,22 +40,22 @@ namespace Yi.Framework.WebCore menuIds = claimlist.Where(u => u.Type == "menuIds").ToList().Select(u => Convert.ToInt32(u.Value)).ToList(); - return new user() + return new User() { - id = resId, - username = claimlist.FirstOrDefault(u => u.Type == ClaimTypes.Name).Value ?? "匿名" + Id = resId, + Username = claimlist.FirstOrDefault(u => u.Type == ClaimTypes.Name).Value ?? "匿名" }; } - public static user GetCurrentUserInfo(this HttpContext httpContext) + public static User GetCurrentUserInfo(this HttpContext httpContext) { IEnumerable claimlist = httpContext.AuthenticateAsync().Result.Principal.Claims; Int32.TryParse(claimlist.FirstOrDefault(u => u.Type == ClaimTypes.Sid).Value, out int resId); - return new user() + return new User() { - id = resId, - username = claimlist.FirstOrDefault(u => u.Type == ClaimTypes.Name).Value ?? "匿名" + Id = resId, + Username = claimlist.FirstOrDefault(u => u.Type == ClaimTypes.Name).Value ?? "匿名" }; } } diff --git a/Yi.Framework.Net6/Yi.Framework.WebCore/Init/DataSeed.cs b/Yi.Framework.Net6/Yi.Framework.WebCore/Init/DataSeed.cs deleted file mode 100644 index 337236ce..00000000 --- a/Yi.Framework.Net6/Yi.Framework.WebCore/Init/DataSeed.cs +++ /dev/null @@ -1,78 +0,0 @@ -using Microsoft.EntityFrameworkCore; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Yi.Framework.Model.ModelFactory; -using Yi.Framework.Model.Models; - -namespace Yi.Framework.WebCore.Init -{ - public class DataSeed - { - public async static Task SeedAsync(IDbContextFactory _DbFactory) - { - var _Db = _DbFactory.ConnWriteOrRead(Common.Enum.WriteAndReadEnum.Write); - if (!_Db.Set().Any()) - { - List menus = new List{ - - new menu{ id=1, menu_name="根",is_show=1,is_top=1}, - new menu{ id=2,icon="mdi-view-dashboard", menu_name="首页",is_show=1,is_top=0,router="/",parentId=1}, - new menu{id=3,icon="mdi-account-box-multiple", menu_name="用户角色管理",is_show=1,is_top=0,parentId=1}, - - new menu{id=4,icon="mdi-account-box", menu_name="用户管理",router="/AdmUser/",is_show=1,is_top=0,parentId=3}, - new menu{id=5, menu_name="get",is_show=0,is_top=0,parentId=4,mould=new mould{mould_name="get",url="/user/getuser" } }, - new menu{id=6, menu_name="update",is_show=0,is_top=0,parentId=4,mould=new mould{mould_name="update",url="/user/updateuser" } }, - new menu{id=7, menu_name="del",is_show=0,is_top=0,parentId=4,mould=new mould{mould_name="del",url="/user/dellistUser" } }, - new menu{id=8, menu_name="add",is_show=0,is_top=0,parentId=4,mould=new mould{mould_name="add",url="/role/adduser" } }, - - new menu{ id=9,icon="mdi-account-circle", menu_name="角色管理",router="/admrole/",is_show=1,is_top=0,parentId=3}, - new menu{id=10, menu_name="get",is_show=0,is_top=0,parentId=9,mould=new mould{mould_name="get",url="/role/getrole" } }, - new menu{id=11, menu_name="update",is_show=0,is_top=0,parentId=9,mould=new mould{mould_name="update",url="/role/updaterole" } }, - new menu{id=12, menu_name="del",is_show=0,is_top=0,parentId=9,mould=new mould{mould_name="del",url="/role/dellistrole" } }, - new menu{id=13, menu_name="add",is_show=0,is_top=0,parentId=9,mould=new mould{mould_name="add",url="/role/addrole" } }, - - - new menu{ id=14,icon="mdi-account-cash", menu_name="角色接口管理",is_show=1,is_top=0,parentId=1}, - - - new menu{ id=15,icon="mdi-clipboard-check-multiple", menu_name="菜单管理",router="/AdmMenu/",is_show=1,is_top=0,parentId=14}, - new menu{id=16, menu_name="get",is_show=0,is_top=0,parentId=15,mould=new mould{mould_name="get",url="/menu/getmenu" } }, - new menu{id=17, menu_name="update",is_show=0,is_top=0,parentId=15,mould=new mould{mould_name="update",url="/menu/updatemenu" } }, - new menu{id=18, menu_name="del",is_show=0,is_top=0,parentId=15,mould=new mould{mould_name="del",url="/menu/dellistmenu" } }, - new menu{id=19, menu_name="add",is_show=0,is_top=0,parentId=15,mould=new mould{mould_name="add",url="/menu/addmenu" } }, - - - - new menu{ id=20,icon="mdi-circle-slice-8", menu_name="接口管理",router="/admMould/",is_show=1,is_top=0,parentId=14}, - new menu{id=21, menu_name="get",is_show=0,is_top=0,parentId=20,mould=new mould{mould_name="get",url="/Mould/getMould" } }, - new menu{id=22, menu_name="update",is_show=0,is_top=0,parentId=20,mould=new mould{mould_name="update",url="/Mould/updateMould" } }, - new menu{id=23, menu_name="del",is_show=0,is_top=0,parentId=20,mould=new mould{mould_name="del",url="/Mould/dellistMould" } }, - new menu{id=24, menu_name="add",is_show=0,is_top=0,parentId=20,mould=new mould{mould_name="add",url="/Mould/addMould" } }, - - new menu{ id=25,icon="mdi-clipboard-account", menu_name="角色菜单分配管理",router="/admRoleMenu/",is_show=1,is_top=0,parentId=14}, - - new menu{ id=26,icon="mdi-clipboard-flow-outline", menu_name="路由管理",is_show=1,is_top=0,parentId=1}, - new menu{ id=27,icon="mdi-account-eye", menu_name="用户信息",router="/userinfo/",is_show=1,is_top=0,parentId=26}, - - }; - - - List roles = new List() { - new role(){role_name="普通用户" }, - new role(){role_name="管理员",menus= menus} - }; - - List users = new List() { - new user(){ username="admin",password="123",roles=roles} - }; - - await _Db.Set().AddRangeAsync(users); - await _Db.SaveChangesAsync(); - Console.WriteLine(nameof(DbContext) + ":数据库初始成功!"); - } - } - } -} diff --git a/Yi.Framework.Net6/Yi.Framework.WebCore/Init/RedisInit.cs b/Yi.Framework.Net6/Yi.Framework.WebCore/Init/RedisInit.cs deleted file mode 100644 index 7856785c..00000000 --- a/Yi.Framework.Net6/Yi.Framework.WebCore/Init/RedisInit.cs +++ /dev/null @@ -1,31 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Yi.Framework.Common.Const; -using Yi.Framework.Core; -using Yi.Framework.DTOModel; - -namespace Yi.Framework.WebCore.Init -{ - public class RedisInit - { - public static void Seed(CacheClientDB _cacheClientDB) - { - var setDto = Common.Helper.JsonHelper.ObjToStr(new SettingDto() - { - ImageList =new List { "默认图片", "默认图片" }, - InitRole = "普通用户", - Title = "YiFramework", - InitIcon = "默认头像" - }); - if (_cacheClientDB.Get(RedisConst.key)==null) - { - _cacheClientDB.Add(RedisConst.key,setDto) ; - } - - Console.WriteLine(nameof(RedisInit) + ":Redis初始成功!"); - } - } -} diff --git a/Yi.Framework.Net6/Yi.Framework.WebCore/MiddlewareExtend/DbExtend.cs b/Yi.Framework.Net6/Yi.Framework.WebCore/MiddlewareExtend/DbExtend.cs deleted file mode 100644 index afc20ff6..00000000 --- a/Yi.Framework.Net6/Yi.Framework.WebCore/MiddlewareExtend/DbExtend.cs +++ /dev/null @@ -1,24 +0,0 @@ -using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Yi.Framework.Common.IOCOptions; -using Yi.Framework.Model; -using Yi.Framework.Model.ModelFactory; - -namespace Yi.Framework.WebCore.MiddlewareExtend -{ - public static class DbExtend - { - public static IServiceCollection AddDbService(this IServiceCollection services) - { - DbContextFactory.MutiDB_Enabled = Appsettings.appBool("MutiDB_Enabled"); - DataContext.DbSelect = Appsettings.app("DbSelect"); - DataContext._connStr = Appsettings.app("DbConn", "WriteUrl"); - services.Configure(Appsettings.appConfiguration("DbConn")); - return services; - } - } -} diff --git a/Yi.Framework.Net6/Yi.Framework.WebCore/MiddlewareExtend/DbSeedInitExtend.cs b/Yi.Framework.Net6/Yi.Framework.WebCore/MiddlewareExtend/DbSeedInitExtend.cs deleted file mode 100644 index d43e2913..00000000 --- a/Yi.Framework.Net6/Yi.Framework.WebCore/MiddlewareExtend/DbSeedInitExtend.cs +++ /dev/null @@ -1,36 +0,0 @@ -using log4net; -using Microsoft.AspNetCore.Builder; -using Microsoft.EntityFrameworkCore; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Yi.Framework.Model.ModelFactory; -using Yi.Framework.WebCore.Init; - -namespace Yi.Framework.WebCore.MiddlewareExtend -{ - public static class DbSeedInitExtend - { - private static readonly ILog log = LogManager.GetLogger(typeof(DbSeedInitExtend)); - public static void UseDbSeedInitService(this IApplicationBuilder app, IDbContextFactory _DbFactory) - { - - if (Appsettings.appBool("DbSeed_Enabled")) - { - if (app == null) throw new ArgumentNullException(nameof(app)); - - try - { - DataSeed.SeedAsync(_DbFactory).Wait(); - } - catch (Exception e) - { - log.Error($"Error occured seeding the Database.\n{e.Message}"); - throw; - } - } - } - } -} diff --git a/Yi.Framework.Net6/Yi.Framework.WebCore/MiddlewareExtend/IocExtension.cs b/Yi.Framework.Net6/Yi.Framework.WebCore/MiddlewareExtend/IocExtension.cs index b7d73f4f..665e61a2 100644 --- a/Yi.Framework.Net6/Yi.Framework.WebCore/MiddlewareExtend/IocExtension.cs +++ b/Yi.Framework.Net6/Yi.Framework.WebCore/MiddlewareExtend/IocExtension.cs @@ -5,7 +5,6 @@ using Microsoft.Extensions.DependencyInjection; using System; using System.IO; using Yi.Framework.Model; -using Yi.Framework.Model.ModelFactory; namespace Yi.Framework.WebCore.MiddlewareExtend { @@ -20,10 +19,7 @@ namespace Yi.Framework.WebCore.MiddlewareExtend //配置文件使用配置 #endregion services.AddSingleton(new Appsettings(configuration)); - #region - //数据库配置 - #endregion - services.AddTransient(); + return services; } diff --git a/Yi.Framework.Net6/Yi.Framework.WebCore/MiddlewareExtend/RedisInitExtend.cs b/Yi.Framework.Net6/Yi.Framework.WebCore/MiddlewareExtend/RedisInitExtend.cs index 010bb42e..63b603a6 100644 --- a/Yi.Framework.Net6/Yi.Framework.WebCore/MiddlewareExtend/RedisInitExtend.cs +++ b/Yi.Framework.Net6/Yi.Framework.WebCore/MiddlewareExtend/RedisInitExtend.cs @@ -7,8 +7,6 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using Yi.Framework.Core; -using Yi.Framework.Model.ModelFactory; -using Yi.Framework.WebCore.Init; namespace Yi.Framework.WebCore.MiddlewareExtend { @@ -24,7 +22,7 @@ namespace Yi.Framework.WebCore.MiddlewareExtend try { - RedisInit.Seed(_cacheClientDB); + //RedisInit.Seed(_cacheClientDB); } catch (Exception e) { diff --git a/Yi.Framework.Net6/Yi.Framework.WebCore/Utility/CustomAutofacModule.cs b/Yi.Framework.Net6/Yi.Framework.WebCore/Utility/CustomAutofacModule.cs index f39b0d8d..26777668 100644 --- a/Yi.Framework.Net6/Yi.Framework.WebCore/Utility/CustomAutofacModule.cs +++ b/Yi.Framework.Net6/Yi.Framework.WebCore/Utility/CustomAutofacModule.cs @@ -12,7 +12,6 @@ using System.Linq; using System.Reflection; using System.Threading.Tasks; using Yi.Framework.Job; -using Yi.Framework.Model.ModelFactory; using Yi.Framework.WebCore.Utility; using Module = Autofac.Module; @@ -35,7 +34,7 @@ namespace Yi.Framework.WebCore.Utility protected override void Load(ContainerBuilder containerBuilder) { - containerBuilder.RegisterType().As().InstancePerDependency().EnableInterfaceInterceptors(); + //containerBuilder.RegisterType().As().InstancePerDependency().EnableInterfaceInterceptors(); containerBuilder.RegisterType< HttpContextAccessor>().As().SingleInstance(); diff --git a/Yi.Framework.Net6/Yi.Framework.WebCore/Yi.Framework.WebCore.csproj b/Yi.Framework.Net6/Yi.Framework.WebCore/Yi.Framework.WebCore.csproj index 95c39335..47494c31 100644 --- a/Yi.Framework.Net6/Yi.Framework.WebCore/Yi.Framework.WebCore.csproj +++ b/Yi.Framework.Net6/Yi.Framework.WebCore/Yi.Framework.WebCore.csproj @@ -32,4 +32,8 @@ + + + + diff --git a/Yi.Framework.Net6/Yi.Framework.sln b/Yi.Framework.Net6/Yi.Framework.sln index 73747fd5..f169cc5a 100644 --- a/Yi.Framework.Net6/Yi.Framework.sln +++ b/Yi.Framework.Net6/Yi.Framework.sln @@ -41,6 +41,10 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Yi.Framework.Job", "Yi.Fram EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Yi.Framework.SMSProcessor", "Yi.Framework.SMSProcessor\Yi.Framework.SMSProcessor.csproj", "{7C58FB7C-9AB5-47CF-ACEB-B784CF820E7E}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Yi.Framework.Repository", "Yi.Framework.Repository\Yi.Framework.Repository.csproj", "{DA96B62F-2D4C-4AFB-937C-5AEA1119A129}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Yi.Framework.Language", "Yi.Framework.Language\Yi.Framework.Language.csproj", "{3047069B-4084-461F-BC9F-023BC60401D1}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -103,6 +107,14 @@ Global {7C58FB7C-9AB5-47CF-ACEB-B784CF820E7E}.Debug|Any CPU.Build.0 = Debug|Any CPU {7C58FB7C-9AB5-47CF-ACEB-B784CF820E7E}.Release|Any CPU.ActiveCfg = Release|Any CPU {7C58FB7C-9AB5-47CF-ACEB-B784CF820E7E}.Release|Any CPU.Build.0 = Release|Any CPU + {DA96B62F-2D4C-4AFB-937C-5AEA1119A129}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {DA96B62F-2D4C-4AFB-937C-5AEA1119A129}.Debug|Any CPU.Build.0 = Debug|Any CPU + {DA96B62F-2D4C-4AFB-937C-5AEA1119A129}.Release|Any CPU.ActiveCfg = Release|Any CPU + {DA96B62F-2D4C-4AFB-937C-5AEA1119A129}.Release|Any CPU.Build.0 = Release|Any CPU + {3047069B-4084-461F-BC9F-023BC60401D1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {3047069B-4084-461F-BC9F-023BC60401D1}.Debug|Any CPU.Build.0 = Debug|Any CPU + {3047069B-4084-461F-BC9F-023BC60401D1}.Release|Any CPU.ActiveCfg = Release|Any CPU + {3047069B-4084-461F-BC9F-023BC60401D1}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -122,6 +134,8 @@ Global {531255B3-9669-4BC1-B4E5-A0C6E0540F0D} = {C90E38FB-69EA-4997-8B3A-2C71EFA65B2B} {F1C990DD-32C3-4F02-83B0-6E52B18B0B17} = {9ABAF6B1-6C02-498A-90A2-ABC1140CF89A} {7C58FB7C-9AB5-47CF-ACEB-B784CF820E7E} = {D6B44435-EAFA-4D55-90D0-3AF80485FB83} + {DA96B62F-2D4C-4AFB-937C-5AEA1119A129} = {DB2506F5-05FD-4E76-940E-41D7AA148550} + {3047069B-4084-461F-BC9F-023BC60401D1} = {9ABAF6B1-6C02-498A-90A2-ABC1140CF89A} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {1ED77A6E-377F-4EEF-A3D0-D65C94657DAF}