提交.Net6版本
@@ -0,0 +1,222 @@
|
||||
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;
|
||||
|
||||
namespace Yi.Framework.ApiMicroservice.Controllers
|
||||
{
|
||||
[ApiController]
|
||||
[Route("api/[controller]/[action]")]
|
||||
public class AccountController : Controller
|
||||
{
|
||||
private readonly ILogger<UserController> _logger;
|
||||
|
||||
private IUserService _userService;
|
||||
private IMenuService _menuService;
|
||||
private RabbitMQInvoker _rabbitMQInvoker;
|
||||
private CacheClientDB _cacheClientDB;
|
||||
private IRoleService _roleService;
|
||||
private IHttpContextAccessor _httpContext;
|
||||
public AccountController(ILogger<UserController> 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;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 登录方法,要返回data:{user,token} token
|
||||
/// </summary>
|
||||
/// <param name="_user"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPost]
|
||||
public async Task<Result> Login(user _user)
|
||||
{
|
||||
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;
|
||||
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();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 不用写,单纯制作日志
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
[HttpPost]
|
||||
public Result Logout()
|
||||
{
|
||||
return Result.Success();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// code为验证码,从redis中判断一下code是否正确
|
||||
/// </summary>
|
||||
/// <param name="_user"></param>
|
||||
/// <param name="code"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPost]
|
||||
public async Task<Result> Register(user _user, string code)
|
||||
{
|
||||
_user.username=_user.username.Trim();
|
||||
if(string.IsNullOrEmpty(_user.username))
|
||||
code = code.Trim();
|
||||
|
||||
string trueCode= _cacheClientDB.Get<string>(RedisConst.keyCode + _user.phone);
|
||||
if (code == trueCode)
|
||||
{
|
||||
//设置默认头像
|
||||
var setting = JsonHelper.StrToObj<SettingDto>(_cacheClientDB.Get<string>(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<role>();
|
||||
_user.roles.Add(await _roleService.GetEntity(u => u.role_name == setting.InitRole));
|
||||
await _userService.Register(_user);
|
||||
|
||||
return Result.Success("恭喜,你已加入我们!");
|
||||
}
|
||||
return Result.Error("验证码有误,请重新输入!");
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 发送短信,需要将生成的sms+code存入redis
|
||||
/// </summary>
|
||||
/// <param name="SMSAddress"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPost]
|
||||
public async Task<Result> 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("该号码已被注册");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 发送邮箱,需要先到数据库判断该邮箱是否被人注册过,到userservice写mail_exist方法,还有接口别忘了。
|
||||
/// </summary>
|
||||
/// <param name="emailAddress"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPost]//邮箱验证
|
||||
public async Task<Result> 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<string>(emailAddress, code, TimeSpan.FromSeconds(10));
|
||||
|
||||
return Result.Success("发送邮件成功,请查看邮箱(可能在垃圾箱)");
|
||||
}
|
||||
else
|
||||
{
|
||||
return Result.Error("该邮箱已被注册");
|
||||
}
|
||||
// 邮箱和验证码都要被记住,然后注册时候比对邮箱和验证码是不是都和现在生成的一样
|
||||
}
|
||||
/// <summary>
|
||||
/// 修改密码
|
||||
/// </summary>
|
||||
/// <param name="pwdDto"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPut]
|
||||
[Authorize]
|
||||
public async Task<Result> 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);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
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<Result> 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();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 该方法不对外暴露
|
||||
/// </summary>
|
||||
/// <param name="type"></param>
|
||||
/// <param name="file"></param>
|
||||
/// <returns></returns>
|
||||
private async Task<string> 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<IActionResult> ExportFile()
|
||||
{
|
||||
var userdata = await _userService.GetAllEntitiesTrueAsync();
|
||||
var userList = userdata.ToList();
|
||||
List<string> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
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<JobController> _logger;
|
||||
private QuartzInvoker _quartzInvoker;
|
||||
public JobController(ILogger<JobController> logger,QuartzInvoker quartzInvoker)
|
||||
{
|
||||
_logger = logger;
|
||||
_quartzInvoker = quartzInvoker;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
[HttpPost]
|
||||
public async Task<Result> startJob()
|
||||
{
|
||||
//任务1
|
||||
//await _quartzInvoker.start("*/1 * * * * ? ", new Quartz.JobKey("test", "my"), "VisitJob");
|
||||
|
||||
//任务2
|
||||
Dictionary<string, object> data = new Dictionary<string, object>()
|
||||
{
|
||||
{JobConst.method,"get" },
|
||||
{JobConst.url,"https://www.baidu.com" }
|
||||
};
|
||||
await _quartzInvoker.start("*/1 * * * * ? ", new Quartz.JobKey("test", "my"), "HttpJob",data: data);
|
||||
return Result.Success();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
[HttpGet]
|
||||
public async Task<Result> getRunJobList()
|
||||
{
|
||||
return Result.Success().SetData(await _quartzInvoker.getRunJobList());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
[HttpGet]
|
||||
public Result getJobClass()
|
||||
{
|
||||
return Result.Success().SetData(_quartzInvoker.getJobClassList());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
[HttpPut]
|
||||
public async Task<Result> stopJob()
|
||||
{
|
||||
await _quartzInvoker.Stop(new Quartz.JobKey("test", "my"));
|
||||
return Result.Success();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
[HttpDelete]
|
||||
public async Task<Result> DeleteJob()
|
||||
{
|
||||
await _quartzInvoker.Delete(new Quartz.JobKey("test", "my"));
|
||||
return Result.Success();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
[HttpPut]
|
||||
public async Task<Result> ResumeJob()
|
||||
{
|
||||
await _quartzInvoker.Resume(new Quartz.JobKey("test", "my"));
|
||||
return Result.Success();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
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;
|
||||
public MenuController(IMenuService menuService)
|
||||
{
|
||||
_menuService = menuService;
|
||||
}
|
||||
/// <summary>
|
||||
/// 这个是要递归的,但是要过滤掉删除的,所以,可以写一个通用过滤掉删除的方法
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
[HttpGet]
|
||||
public async Task<Result> GetMenuInMould()
|
||||
{
|
||||
return Result.Success().SetData(await _menuService.GetMenuInMould());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 更
|
||||
/// </summary>
|
||||
/// <param name="_menu"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPut]
|
||||
public async Task<Result> UpdateMenu(menu _menu)
|
||||
{
|
||||
await _menuService.UpdateAsync(_menu);
|
||||
return Result.Success();
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 删
|
||||
/// </summary>
|
||||
/// <param name="_ids"></param>
|
||||
/// <returns></returns>
|
||||
[HttpDelete]
|
||||
public async Task<Result> DelListMenu(List<int> _ids)
|
||||
{
|
||||
await _menuService.DelListByUpdateAsync(_ids);
|
||||
return Result.Success();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 增
|
||||
/// 现在,top菜单只允许为一个
|
||||
/// </summary>
|
||||
/// <param name="_menu"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPost]
|
||||
public async Task<Result> AddTopMenu(menu _menu)
|
||||
{
|
||||
await _menuService.AddTopMenu(_menu);
|
||||
return Result.Success();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 给一个菜单设置一个接口,Id1为菜单id,Id2为接口id
|
||||
/// 用于给菜单设置接口
|
||||
/// </summary>
|
||||
/// <param name="idDto"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPost]
|
||||
public async Task<Result> SetMouldByMenu(IdDto<int> idDto)
|
||||
{
|
||||
await _menuService.SetMouldByMenu(idDto.id1, idDto.id2);
|
||||
return Result.Success();
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 给一个菜单添加子节点(注意:添加,不是覆盖)
|
||||
/// </summary>
|
||||
/// <param name="childrenDto"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPost]
|
||||
public async Task<Result> AddChildrenMenu(ChildrenDto<menu> childrenDto)
|
||||
{
|
||||
await _menuService.AddChildrenMenu(childrenDto.parentId, childrenDto.data);
|
||||
return Result.Success();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取用户的目录菜单,不包含接口
|
||||
/// 用于账户信息页面,显示这个用户有哪些菜单,需要并列
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
[HttpGet]
|
||||
public async Task<Result> GetTopMenusByHttpUser()
|
||||
{
|
||||
HttpContext.GetCurrentUserInfo(out List<int> menuIds);
|
||||
|
||||
return Result.Success().SetData(await _menuService.GetTopMenusByTopMenuIds(menuIds));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
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<Result> GetMould()
|
||||
{
|
||||
return Result.Success().SetData(await _mouldService.GetAllEntitiesTrueAsync());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 更
|
||||
/// </summary>
|
||||
/// <param name="_mould"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPut]
|
||||
public async Task<Result> UpdateMould(mould _mould)
|
||||
{
|
||||
await _mouldService.UpdateAsync(_mould);
|
||||
return Result.Success();
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 删
|
||||
/// </summary>
|
||||
/// <param name="_ids"></param>
|
||||
/// <returns></returns>
|
||||
[HttpDelete]
|
||||
public async Task<Result> DelListMould(List<int> _ids)
|
||||
{
|
||||
await _mouldService.DelListByUpdateAsync(_ids);
|
||||
return Result.Success();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 增
|
||||
/// </summary>
|
||||
/// <param name="_mould"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPost]
|
||||
public async Task<Result> AddMould(mould _mould)
|
||||
{
|
||||
await _mouldService.AddAsync(_mould);
|
||||
return Result.Success();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
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<Result> GetRole()
|
||||
{
|
||||
return Result.Success().SetData(await _roleService.GetAllEntitiesTrueAsync());
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 更
|
||||
/// </summary>
|
||||
/// <param name="_role"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPut]
|
||||
public async Task<Result> UpdateRole(role _role)
|
||||
{
|
||||
await _roleService.UpdateAsync(_role);
|
||||
return Result.Success();
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 删
|
||||
/// </summary>
|
||||
/// <param name="_ids"></param>
|
||||
/// <returns></returns>
|
||||
[HttpDelete]
|
||||
public async Task<Result> DelListRole(List<int> _ids)
|
||||
{
|
||||
await _roleService.DelListByUpdateAsync(_ids);
|
||||
return Result.Success();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 增
|
||||
/// </summary>
|
||||
/// <param name="_role"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPost]
|
||||
public async Task<Result> AddRole(role _role)
|
||||
{
|
||||
await _roleService.AddAsync(_role);
|
||||
return Result.Success();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 根据用户id得到该用户有哪些角色
|
||||
/// 用于显示用户详情中的角色说明
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
[HttpGet]
|
||||
public async Task<Result> GetRolesByUserId(int userId)
|
||||
{
|
||||
|
||||
return Result.Success().SetData(await _roleService.GetRolesByUserId(userId));
|
||||
}
|
||||
/// <summary>
|
||||
/// 给角色设置菜单,多个角色与多个菜单,让每一个角色都设置,ids1为角色,ids2为菜单
|
||||
/// 用于设置角色
|
||||
/// </summary>
|
||||
/// <param name="idsListDto"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPost]
|
||||
public async Task<Result> SetMenuByRole(IdsListDto<int> idsListDto)
|
||||
{
|
||||
await _roleService.SetMenusByRolesId(idsListDto.ids2, idsListDto.ids1);
|
||||
return Result.Success();
|
||||
}
|
||||
/// <summary>
|
||||
/// 用于给角色设置菜单的时候,点击一个角色,显示这个角色拥有的并列的菜单
|
||||
/// </summary>
|
||||
/// <param name="roleId"></param>
|
||||
/// <returns></returns>
|
||||
[HttpGet]
|
||||
public async Task<Result> GetTopMenusByRoleId(int roleId)
|
||||
{
|
||||
|
||||
return Result.Success().SetData(await _roleService.GetTopMenusByRoleId(roleId) ); ;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
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<SettingController> _logger;
|
||||
private readonly CacheClientDB _cacheClientDB;
|
||||
|
||||
public SettingController(ILogger<SettingController> logger, CacheClientDB cacheClientDB)
|
||||
{
|
||||
_logger = logger;
|
||||
_cacheClientDB = cacheClientDB;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 查
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
[HttpGet]
|
||||
public Result GetSetting()
|
||||
{
|
||||
var setDto = Common.Helper.JsonHelper.StrToObj<SettingDto>(_cacheClientDB.Get<string>(RedisConst.key));
|
||||
return Result.Success().SetData( setDto);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 更
|
||||
/// </summary>
|
||||
/// <param name="settingDto"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPut]
|
||||
public Result UpdateSetting(SettingDto settingDto)
|
||||
{
|
||||
var setDto = Common.Helper.JsonHelper.ObjToStr(settingDto);
|
||||
|
||||
_cacheClientDB.Set(RedisConst.key, setDto);
|
||||
return Result.Success();
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
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.Models;
|
||||
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 UserController : ControllerBase
|
||||
{
|
||||
private readonly ILogger<UserController> _logger;
|
||||
|
||||
private IUserService _userService;
|
||||
public UserController(ILogger<UserController> logger, IUserService userService)
|
||||
{
|
||||
_logger = logger;
|
||||
_userService = userService;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 查
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
[HttpGet]
|
||||
public async Task<Result> GetUser()
|
||||
{
|
||||
return Result.Success().SetData(await _userService.GetAllEntitiesTrueAsync());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 更
|
||||
/// </summary>
|
||||
/// <param name="_user"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPut]
|
||||
public async Task<Result> UpdateUser(user _user)
|
||||
{
|
||||
await _userService.UpdateAsync(_user);
|
||||
return Result.Success();
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 删
|
||||
/// </summary>
|
||||
/// <param name="_ids"></param>
|
||||
/// <returns></returns>
|
||||
[HttpDelete]
|
||||
public async Task<Result> DelListUser(List<int> _ids)
|
||||
{
|
||||
await _userService.DelListByUpdateAsync(_ids);
|
||||
return Result.Success();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 增
|
||||
/// </summary>
|
||||
/// <param name="_user"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPost]
|
||||
public async Task<Result> AddUser(user _user)
|
||||
{
|
||||
await _userService.AddAsync(_user);
|
||||
return Result.Success();
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// SetRoleByUser
|
||||
/// 给多个用户设置多个角色,ids有用户id与 角色列表ids,多对多,ids1用户,ids2为角色
|
||||
/// 用户设置给用户设置角色
|
||||
/// </summary>
|
||||
/// <param name="idsListDto"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPost]
|
||||
public async Task<Result> SetRoleByUser(IdsListDto<int> idsListDto)
|
||||
{
|
||||
await _userService.SetRoleByUser(idsListDto.ids2, idsListDto.ids1);
|
||||
return Result.Success();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 根据http上下文的用户得到该用户信息,关联角色
|
||||
/// 用于显示账号信息页中的用户信息和角色信息
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
[HttpGet]
|
||||
public async Task<Result> GetUserInRolesByHttpUser()
|
||||
{
|
||||
var _user = HttpContext.GetCurrentUserInfo();
|
||||
return Result.Success().SetData( await _userService.GetUserInRolesByHttpUser(_user.id));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 得到登录用户的递归菜单,放到导航栏
|
||||
/// 用户放到导航栏中
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
[HttpGet]
|
||||
public async Task<Result> GetMenuByHttpUser()
|
||||
{
|
||||
HttpContext.GetCurrentUserInfo(out var allMenuIds);
|
||||
return Result.Success().SetData(await _userService.GetMenuByHttpUser(allMenuIds));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 得到请求模型
|
||||
/// </summary>
|
||||
/// <param name="router"></param>
|
||||
/// <returns></returns>
|
||||
[HttpGet]
|
||||
public async Task<Result> GetAxiosByRouter(string router)
|
||||
{
|
||||
|
||||
var _user = HttpContext.GetCurrentUserInfo(out List<int> menuIds);
|
||||
if (menuIds == null)
|
||||
{
|
||||
return Result.Error();
|
||||
}
|
||||
var menuList= await _userService.GetAxiosByRouter(router, _user.id, 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);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<log4net>
|
||||
<!-- 将日志以回滚文件的形式写到文件中 -->
|
||||
<!-- 按日期切分日志文件,并将日期作为日志文件的名字 -->
|
||||
<!--Error-->
|
||||
<appender name="ErrorLog" type="log4net.Appender.RollingFileAppender">
|
||||
<!--不加utf-8编码格式,中文字符将显示成乱码-->
|
||||
<param name="Encoding" value="utf-8" />
|
||||
<file value="log/"/>
|
||||
<appendToFile value="true" />
|
||||
<rollingStyle value="Date" />
|
||||
<!--日期的格式,每天换一个文件记录,如不设置则永远只记录一天的日志,需设置-->
|
||||
<datePattern value=""GlobalExceptionLogs_"yyyyMMdd".log"" />
|
||||
<!--日志文件名是否为静态-->
|
||||
<StaticLogFileName value="false"/>
|
||||
<!--多线程时采用最小锁定-->
|
||||
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
|
||||
<!--布局(向用户显示最后经过格式化的输出信息)-->
|
||||
<layout type="log4net.Layout.PatternLayout">
|
||||
<conversionPattern value="%date| %-5level %newline%message%newline--------------------------------%newline" />
|
||||
</layout>
|
||||
<filter type="log4net.Filter.LevelRangeFilter">
|
||||
<levelMin value="ERROR" />
|
||||
<levelMax value="FATAL" />
|
||||
</filter>
|
||||
</appender>
|
||||
<!--Error-->
|
||||
|
||||
|
||||
|
||||
<!--Info-->
|
||||
<appender name="InfoLog" type="log4net.Appender.RollingFileAppender">
|
||||
<!--不加utf-8编码格式,中文字符将显示成乱码-->
|
||||
<param name="Encoding" value="utf-8" />
|
||||
<!--定义文件存放位置-->
|
||||
<file value="log/"/>
|
||||
<appendToFile value="true" />
|
||||
<rollingStyle value="Date" />
|
||||
<!--日志文件名是否为静态-->
|
||||
<StaticLogFileName value="false"/>
|
||||
<!--日期的格式,每天换一个文件记录,如不设置则永远只记录一天的日志,需设置-->
|
||||
<datePattern value=""GlobalInfoLogs_"yyyyMMdd".log"" />
|
||||
<!--多线程时采用最小锁定-->
|
||||
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
|
||||
<!--布局(向用户显示最后经过格式化的输出信息)-->
|
||||
<layout type="log4net.Layout.PatternLayout">
|
||||
<conversionPattern value="%date| %-5level%c %newline%message%newline--------------------------------%newline" />
|
||||
</layout>
|
||||
<filter type="log4net.Filter.LevelRangeFilter">
|
||||
<levelMin value="DEBUG" />
|
||||
<levelMax value="WARN" />
|
||||
</filter>
|
||||
</appender>
|
||||
<!--Info-->
|
||||
|
||||
<root>
|
||||
<!-- 控制级别,由低到高:ALL|DEBUG|INFO|WARN|ERROR|FATAL|OFF -->
|
||||
<!-- 比如定义级别为INFO,则INFO级别向下的级别,比如DEBUG日志将不会被记录 -->
|
||||
<!-- 如果没有定义LEVEL的值,则缺省为DEBUG -->
|
||||
<level value="ALL" />
|
||||
<!-- 按日期切分日志文件,并将日期作为日志文件的名字 -->
|
||||
<appender-ref ref="ErrorLog" />
|
||||
<appender-ref ref="InfoLog" />
|
||||
</root>
|
||||
</log4net>
|
||||
157
Yi.Framework.Net6/Yi.Framework.ApiMicroservice/Program.cs
Normal file
@@ -0,0 +1,157 @@
|
||||
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;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
builder.Host.ConfigureAppConfiguration((hostBuilderContext, configurationBuilder) =>
|
||||
{
|
||||
configurationBuilder.AddCommandLine(args);
|
||||
configurationBuilder.AddJsonFileService();
|
||||
#region
|
||||
//Apollo<6C><6F><EFBFBD><EFBFBD>
|
||||
#endregion
|
||||
configurationBuilder.AddApolloService("Yi");
|
||||
});
|
||||
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
|
||||
builder.Host.ConfigureContainer<ContainerBuilder>(containerBuilder =>
|
||||
{
|
||||
#region
|
||||
//<2F><><EFBFBD><EFBFBD>Module<6C><65><EFBFBD><EFBFBD>ע<EFBFBD><D7A2>
|
||||
#endregion
|
||||
containerBuilder.RegisterModule<CustomAutofacModule>();
|
||||
});
|
||||
builder.Host.ConfigureLogging(loggingBuilder =>
|
||||
{
|
||||
loggingBuilder.AddFilter("System", Microsoft.Extensions.Logging.LogLevel.Warning);
|
||||
loggingBuilder.AddFilter("Microsoft", Microsoft.Extensions.Logging.LogLevel.Warning);
|
||||
loggingBuilder.AddLog4Net();
|
||||
});
|
||||
#region
|
||||
//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
||||
//builder.Host.ConfigureWebHostDefaults(webBuilder =>
|
||||
// {
|
||||
// //webBuilder.UseStartup<Startup>();
|
||||
// });
|
||||
#endregion
|
||||
//-----------------------------------------------------------------------------------------------------------
|
||||
#region
|
||||
//Ioc<6F><63><EFBFBD><EFBFBD>
|
||||
#endregion
|
||||
builder.Services.AddIocService(builder.Configuration);
|
||||
|
||||
#region
|
||||
//Quartz<74><7A><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
||||
#endregion
|
||||
builder.Services.AddQuartzService();
|
||||
#region
|
||||
//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>+<2B><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
||||
#endregion
|
||||
builder.Services.AddControllers(optios => {
|
||||
//optios.Filters.Add(typeof(CustomExceptionFilterAttribute));
|
||||
}).AddJsonFileService();
|
||||
#region
|
||||
//Swagger<65><72><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
||||
#endregion
|
||||
builder.Services.AddSwaggerService<Program>();
|
||||
#region
|
||||
//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
||||
#endregion
|
||||
builder.Services.AddCorsService();
|
||||
#region
|
||||
//Jwt<77><74>Ȩ<EFBFBD><C8A8><EFBFBD><EFBFBD>
|
||||
#endregion
|
||||
builder.Services.AddJwtService();
|
||||
#region
|
||||
//<2F><><EFBFBD>ݿ<EFBFBD><DDBF><EFBFBD><EFBFBD><EFBFBD>
|
||||
#endregion
|
||||
builder.Services.AddDbService();
|
||||
#region
|
||||
//Redis<69><73><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
||||
#endregion
|
||||
builder.Services.AddRedisService();
|
||||
#region
|
||||
//RabbitMQ<4D><51><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
||||
#endregion
|
||||
builder.Services.AddRabbitMQService();
|
||||
#region
|
||||
//ElasticSeach<63><68><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
||||
#endregion
|
||||
builder.Services.AddElasticSeachService();
|
||||
#region
|
||||
//<2F><><EFBFBD>ŷ<EFBFBD><C5B7><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
||||
#endregion
|
||||
builder.Services.AddSMSService();
|
||||
#region
|
||||
//CAP<41><50><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
||||
#endregion
|
||||
builder.Services.AddCAPService<Program>();
|
||||
//-----------------------------------------------------------------------------------------------------------
|
||||
var app = builder.Build();
|
||||
//if (app.Environment.IsDevelopment())
|
||||
{
|
||||
#region
|
||||
//<2F><><EFBFBD><EFBFBD>ҳ<EFBFBD><D2B3>ע<EFBFBD><D7A2>
|
||||
#endregion
|
||||
app.UseDeveloperExceptionPage();
|
||||
#region
|
||||
//Swagger<65><72><EFBFBD><EFBFBD>ע<EFBFBD><D7A2>
|
||||
#endregion
|
||||
app.UseSwaggerService();
|
||||
}
|
||||
#region
|
||||
//<2F><><EFBFBD><EFBFBD>ץȡ<D7A5><C8A1><EFBFBD><EFBFBD>ע<EFBFBD><D7A2>
|
||||
#endregion
|
||||
app.UseErrorHandlingService();
|
||||
#region
|
||||
//<2F><>̬<EFBFBD>ļ<EFBFBD>ע<EFBFBD><D7A2>
|
||||
#endregion
|
||||
//app.UseStaticFiles();
|
||||
#region
|
||||
//HttpsRedirectionע<6E><D7A2>
|
||||
#endregion
|
||||
app.UseHttpsRedirection();
|
||||
#region
|
||||
//·<><C2B7>ע<EFBFBD><D7A2>
|
||||
#endregion
|
||||
app.UseRouting();
|
||||
#region
|
||||
//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ע<EFBFBD><D7A2>
|
||||
#endregion
|
||||
app.UseCorsService();
|
||||
#region
|
||||
//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ע<EFBFBD><D7A2>
|
||||
#endregion
|
||||
app.UseHealthCheckMiddleware();
|
||||
#region
|
||||
//<2F><>Ȩע<C8A8><D7A2>
|
||||
#endregion
|
||||
app.UseAuthentication();
|
||||
#region
|
||||
//<2F><>Ȩע<C8A8><D7A2>
|
||||
#endregion
|
||||
app.UseAuthorization();
|
||||
#region
|
||||
//Consul<75><6C><EFBFBD><EFBFBD>ע<EFBFBD><D7A2>
|
||||
#endregion
|
||||
app.UseConsulService();
|
||||
#region
|
||||
//<2F><><EFBFBD>ݿ<EFBFBD><DDBF><EFBFBD><EFBFBD><EFBFBD>ע<EFBFBD><D7A2>
|
||||
#endregion
|
||||
app.UseDbSeedInitService(app.Services.GetService<IDbContextFactory>());
|
||||
#region
|
||||
//redis<69><73><EFBFBD><EFBFBD>ע<EFBFBD><D7A2>
|
||||
#endregion
|
||||
app.UseRedisSeedInitService(app.Services.GetService<CacheClientDB>());
|
||||
#region
|
||||
//Endpointsע<73><D7A2>
|
||||
#endregion
|
||||
app.UseEndpoints(endpoints =>
|
||||
{
|
||||
endpoints.MapControllers();
|
||||
});
|
||||
app.Run();
|
||||
278
Yi.Framework.Net6/Yi.Framework.ApiMicroservice/SwaggerDoc.xml
Normal file
@@ -0,0 +1,278 @@
|
||||
<?xml version="1.0"?>
|
||||
<doc>
|
||||
<assembly>
|
||||
<name>Yi.Framework.ApiMicroservice</name>
|
||||
</assembly>
|
||||
<members>
|
||||
<member name="M:Yi.Framework.ApiMicroservice.Controllers.AccountController.Login(Yi.Framework.Model.Models.user)">
|
||||
<summary>
|
||||
登录方法,要返回data:{user,token} token
|
||||
</summary>
|
||||
<param name="_user"></param>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:Yi.Framework.ApiMicroservice.Controllers.AccountController.Logout">
|
||||
<summary>
|
||||
不用写,单纯制作日志
|
||||
</summary>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:Yi.Framework.ApiMicroservice.Controllers.AccountController.Register(Yi.Framework.Model.Models.user,System.String)">
|
||||
<summary>
|
||||
code为验证码,从redis中判断一下code是否正确
|
||||
</summary>
|
||||
<param name="_user"></param>
|
||||
<param name="code"></param>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:Yi.Framework.ApiMicroservice.Controllers.AccountController.SendSMS(System.String)">
|
||||
<summary>
|
||||
发送短信,需要将生成的sms+code存入redis
|
||||
</summary>
|
||||
<param name="SMSAddress"></param>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:Yi.Framework.ApiMicroservice.Controllers.AccountController.Email(System.String)">
|
||||
<summary>
|
||||
发送邮箱,需要先到数据库判断该邮箱是否被人注册过,到userservice写mail_exist方法,还有接口别忘了。
|
||||
</summary>
|
||||
<param name="emailAddress"></param>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:Yi.Framework.ApiMicroservice.Controllers.AccountController.ChangePassword(Yi.Framework.DTOModel.ChangePwdDto)">
|
||||
<summary>
|
||||
修改密码
|
||||
</summary>
|
||||
<param name="pwdDto"></param>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:Yi.Framework.ApiMicroservice.Controllers.FileController.Upload(System.String,Microsoft.AspNetCore.Http.IFormFile)">
|
||||
<summary>
|
||||
该方法不对外暴露
|
||||
</summary>
|
||||
<param name="type"></param>
|
||||
<param name="file"></param>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:Yi.Framework.ApiMicroservice.Controllers.JobController.startJob">
|
||||
<summary>
|
||||
|
||||
</summary>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:Yi.Framework.ApiMicroservice.Controllers.JobController.getRunJobList">
|
||||
<summary>
|
||||
|
||||
</summary>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:Yi.Framework.ApiMicroservice.Controllers.JobController.getJobClass">
|
||||
<summary>
|
||||
|
||||
</summary>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:Yi.Framework.ApiMicroservice.Controllers.JobController.stopJob">
|
||||
<summary>
|
||||
|
||||
</summary>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:Yi.Framework.ApiMicroservice.Controllers.JobController.DeleteJob">
|
||||
<summary>
|
||||
|
||||
</summary>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:Yi.Framework.ApiMicroservice.Controllers.JobController.ResumeJob">
|
||||
<summary>
|
||||
|
||||
</summary>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:Yi.Framework.ApiMicroservice.Controllers.MenuController.GetMenuInMould">
|
||||
<summary>
|
||||
这个是要递归的,但是要过滤掉删除的,所以,可以写一个通用过滤掉删除的方法
|
||||
</summary>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:Yi.Framework.ApiMicroservice.Controllers.MenuController.UpdateMenu(Yi.Framework.Model.Models.menu)">
|
||||
<summary>
|
||||
更
|
||||
</summary>
|
||||
<param name="_menu"></param>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:Yi.Framework.ApiMicroservice.Controllers.MenuController.DelListMenu(System.Collections.Generic.List{System.Int32})">
|
||||
<summary>
|
||||
删
|
||||
</summary>
|
||||
<param name="_ids"></param>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:Yi.Framework.ApiMicroservice.Controllers.MenuController.AddTopMenu(Yi.Framework.Model.Models.menu)">
|
||||
<summary>
|
||||
增
|
||||
现在,top菜单只允许为一个
|
||||
</summary>
|
||||
<param name="_menu"></param>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:Yi.Framework.ApiMicroservice.Controllers.MenuController.SetMouldByMenu(Yi.Framework.DTOModel.IdDto{System.Int32})">
|
||||
<summary>
|
||||
给一个菜单设置一个接口,Id1为菜单id,Id2为接口id
|
||||
用于给菜单设置接口
|
||||
</summary>
|
||||
<param name="idDto"></param>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:Yi.Framework.ApiMicroservice.Controllers.MenuController.AddChildrenMenu(Yi.Framework.DTOModel.ChildrenDto{Yi.Framework.Model.Models.menu})">
|
||||
<summary>
|
||||
给一个菜单添加子节点(注意:添加,不是覆盖)
|
||||
</summary>
|
||||
<param name="childrenDto"></param>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:Yi.Framework.ApiMicroservice.Controllers.MenuController.GetTopMenusByHttpUser">
|
||||
<summary>
|
||||
获取用户的目录菜单,不包含接口
|
||||
用于账户信息页面,显示这个用户有哪些菜单,需要并列
|
||||
</summary>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:Yi.Framework.ApiMicroservice.Controllers.MouldController.UpdateMould(Yi.Framework.Model.Models.mould)">
|
||||
<summary>
|
||||
更
|
||||
</summary>
|
||||
<param name="_mould"></param>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:Yi.Framework.ApiMicroservice.Controllers.MouldController.DelListMould(System.Collections.Generic.List{System.Int32})">
|
||||
<summary>
|
||||
删
|
||||
</summary>
|
||||
<param name="_ids"></param>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:Yi.Framework.ApiMicroservice.Controllers.MouldController.AddMould(Yi.Framework.Model.Models.mould)">
|
||||
<summary>
|
||||
增
|
||||
</summary>
|
||||
<param name="_mould"></param>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:Yi.Framework.ApiMicroservice.Controllers.RoleController.UpdateRole(Yi.Framework.Model.Models.role)">
|
||||
<summary>
|
||||
更
|
||||
</summary>
|
||||
<param name="_role"></param>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:Yi.Framework.ApiMicroservice.Controllers.RoleController.DelListRole(System.Collections.Generic.List{System.Int32})">
|
||||
<summary>
|
||||
删
|
||||
</summary>
|
||||
<param name="_ids"></param>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:Yi.Framework.ApiMicroservice.Controllers.RoleController.AddRole(Yi.Framework.Model.Models.role)">
|
||||
<summary>
|
||||
增
|
||||
</summary>
|
||||
<param name="_role"></param>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:Yi.Framework.ApiMicroservice.Controllers.RoleController.GetRolesByUserId(System.Int32)">
|
||||
<summary>
|
||||
根据用户id得到该用户有哪些角色
|
||||
用于显示用户详情中的角色说明
|
||||
</summary>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:Yi.Framework.ApiMicroservice.Controllers.RoleController.SetMenuByRole(Yi.Framework.DTOModel.IdsListDto{System.Int32})">
|
||||
<summary>
|
||||
给角色设置菜单,多个角色与多个菜单,让每一个角色都设置,ids1为角色,ids2为菜单
|
||||
用于设置角色
|
||||
</summary>
|
||||
<param name="idsListDto"></param>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:Yi.Framework.ApiMicroservice.Controllers.RoleController.GetTopMenusByRoleId(System.Int32)">
|
||||
<summary>
|
||||
用于给角色设置菜单的时候,点击一个角色,显示这个角色拥有的并列的菜单
|
||||
</summary>
|
||||
<param name="roleId"></param>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:Yi.Framework.ApiMicroservice.Controllers.SettingController.GetSetting">
|
||||
<summary>
|
||||
查
|
||||
</summary>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:Yi.Framework.ApiMicroservice.Controllers.SettingController.UpdateSetting(Yi.Framework.DTOModel.SettingDto)">
|
||||
<summary>
|
||||
更
|
||||
</summary>
|
||||
<param name="settingDto"></param>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:Yi.Framework.ApiMicroservice.Controllers.UserController.GetUser">
|
||||
<summary>
|
||||
查
|
||||
</summary>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:Yi.Framework.ApiMicroservice.Controllers.UserController.UpdateUser(Yi.Framework.Model.Models.user)">
|
||||
<summary>
|
||||
更
|
||||
</summary>
|
||||
<param name="_user"></param>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:Yi.Framework.ApiMicroservice.Controllers.UserController.DelListUser(System.Collections.Generic.List{System.Int32})">
|
||||
<summary>
|
||||
删
|
||||
</summary>
|
||||
<param name="_ids"></param>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:Yi.Framework.ApiMicroservice.Controllers.UserController.AddUser(Yi.Framework.Model.Models.user)">
|
||||
<summary>
|
||||
增
|
||||
</summary>
|
||||
<param name="_user"></param>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:Yi.Framework.ApiMicroservice.Controllers.UserController.SetRoleByUser(Yi.Framework.DTOModel.IdsListDto{System.Int32})">
|
||||
<summary>
|
||||
SetRoleByUser
|
||||
给多个用户设置多个角色,ids有用户id与 角色列表ids,多对多,ids1用户,ids2为角色
|
||||
用户设置给用户设置角色
|
||||
</summary>
|
||||
<param name="idsListDto"></param>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:Yi.Framework.ApiMicroservice.Controllers.UserController.GetUserInRolesByHttpUser">
|
||||
<summary>
|
||||
根据http上下文的用户得到该用户信息,关联角色
|
||||
用于显示账号信息页中的用户信息和角色信息
|
||||
</summary>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:Yi.Framework.ApiMicroservice.Controllers.UserController.GetMenuByHttpUser">
|
||||
<summary>
|
||||
得到登录用户的递归菜单,放到导航栏
|
||||
用户放到导航栏中
|
||||
</summary>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:Yi.Framework.ApiMicroservice.Controllers.UserController.GetAxiosByRouter(System.String)">
|
||||
<summary>
|
||||
得到请求模型
|
||||
</summary>
|
||||
<param name="router"></param>
|
||||
<returns></returns>
|
||||
</member>
|
||||
</members>
|
||||
</doc>
|
||||
@@ -0,0 +1,40 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net6.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
|
||||
<DocumentationFile>D:\CC.Yi\CC.Yi\Yi.Framework\Yi.Framework.ApiMicroservice\SwaggerDoc.xml</DocumentationFile>
|
||||
<NoWarn>1701;1702;CS1591</NoWarn>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Remove="wwwrooot\**" />
|
||||
<Content Remove="wwwrooot\**" />
|
||||
<EmbeddedResource Remove="wwwrooot\**" />
|
||||
<None Remove="wwwrooot\**" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="6.0.1">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Yi.Framework.DTOModel\Yi.Framework.DTOModel.csproj" />
|
||||
<ProjectReference Include="..\Yi.Framework.Interface\Yi.Framework.Interface.csproj" />
|
||||
<ProjectReference Include="..\Yi.Framework.Model\Yi.Framework.Model.csproj" />
|
||||
<ProjectReference Include="..\Yi.Framework.Service\Yi.Framework.Service.csproj" />
|
||||
<ProjectReference Include="..\Yi.Framework.WebCore\Yi.Framework.WebCore.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Folder Include="wwwroot\file\" />
|
||||
<Folder Include="wwwroot\image\" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
After Width: | Height: | Size: 47 KiB |
|
After Width: | Height: | Size: 30 KiB |
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 5.7 KiB |
|
After Width: | Height: | Size: 30 KiB |
|
After Width: | Height: | Size: 47 KiB |
|
After Width: | Height: | Size: 18 KiB |
@@ -0,0 +1,26 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Yi.Framework.AuthenticationCenter.Controllers
|
||||
{
|
||||
[ApiController]
|
||||
[Route("[controller]")]
|
||||
public class WeatherForecastController : ControllerBase
|
||||
{
|
||||
private static readonly string[] Summaries = new[]
|
||||
{
|
||||
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
|
||||
};
|
||||
|
||||
private readonly ILogger<WeatherForecastController> _logger;
|
||||
|
||||
public WeatherForecastController(ILogger<WeatherForecastController> logger)
|
||||
{
|
||||
_logger = logger;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Yi.Framework.AuthenticationCenter
|
||||
{
|
||||
public class Program
|
||||
{
|
||||
public static void Main(string[] args)
|
||||
{
|
||||
CreateHostBuilder(args).Build().Run();
|
||||
}
|
||||
|
||||
public static IHostBuilder CreateHostBuilder(string[] args) =>
|
||||
Host.CreateDefaultBuilder(args)
|
||||
.ConfigureWebHostDefaults(webBuilder =>
|
||||
{
|
||||
webBuilder.UseStartup<Startup>();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.HttpsPolicy;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.OpenApi.Models;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Yi.Framework.AuthenticationCenter
|
||||
{
|
||||
public class Startup
|
||||
{
|
||||
public Startup(IConfiguration configuration)
|
||||
{
|
||||
Configuration = configuration;
|
||||
}
|
||||
|
||||
public IConfiguration Configuration { get; }
|
||||
|
||||
// This method gets called by the runtime. Use this method to add services to the container.
|
||||
public void ConfigureServices(IServiceCollection services)
|
||||
{
|
||||
|
||||
services.AddControllers();
|
||||
services.AddSwaggerGen(c =>
|
||||
{
|
||||
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Yi.Framework.AuthenticationCenter", Version = "v1" });
|
||||
});
|
||||
}
|
||||
|
||||
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
|
||||
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
|
||||
{
|
||||
if (env.IsDevelopment())
|
||||
{
|
||||
app.UseDeveloperExceptionPage();
|
||||
app.UseSwagger();
|
||||
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Yi.Framework.AuthenticationCenter v1"));
|
||||
}
|
||||
|
||||
app.UseHttpsRedirection();
|
||||
|
||||
app.UseRouting();
|
||||
|
||||
app.UseAuthorization();
|
||||
|
||||
app.UseEndpoints(endpoints =>
|
||||
{
|
||||
endpoints.MapControllers();
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net6.0</TargetFramework>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
16
Yi.Framework.Net6/Yi.Framework.Common/Const/DbConst.cs
Normal file
@@ -0,0 +1,16 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Yi.Framework.Common.Const
|
||||
{
|
||||
public class DbConst
|
||||
{
|
||||
public const string Mysql = "Mysql";
|
||||
public const string Sqlite = "Sqlite";
|
||||
public const string Sqlserver = "Sqlserver";
|
||||
public const string Oracle = "Oracle";
|
||||
}
|
||||
}
|
||||
14
Yi.Framework.Net6/Yi.Framework.Common/Const/FileConst.cs
Normal file
@@ -0,0 +1,14 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Yi.Framework.Common.Const
|
||||
{
|
||||
public class FileConst
|
||||
{
|
||||
public const string Image = "Image";
|
||||
public const string File = "File";
|
||||
}
|
||||
}
|
||||
17
Yi.Framework.Net6/Yi.Framework.Common/Const/JobConst.cs
Normal file
@@ -0,0 +1,17 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Yi.Framework.Common.Const
|
||||
{
|
||||
public class JobConst
|
||||
{
|
||||
|
||||
public const string url = nameof(url);
|
||||
|
||||
public const string method = nameof(method);
|
||||
}
|
||||
|
||||
}
|
||||
12
Yi.Framework.Net6/Yi.Framework.Common/Const/JwtConst.cs
Normal file
@@ -0,0 +1,12 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace Yi.Framework.Common.Const
|
||||
{
|
||||
public class JwtConst
|
||||
{
|
||||
public const string SecurityKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDI2a2EJ7m872v0afyoSDJT2o1+SitIeJSWtLJU8/Wz2m7gStexajkeD+Lka6DSTy8gt9UwfgVQo6uKjVLG5Ex7PiGOODVqAEghBuS7JzIYU5RvI543nNDAPfnJsas96mSA7L/mD7RTE2drj6hf3oZjJpMPZUQI/B1Qjb5H3K3PNwIDAQAB";
|
||||
public const string Domain = "https://localhost:44329";
|
||||
}
|
||||
}
|
||||
15
Yi.Framework.Net6/Yi.Framework.Common/Const/RabbitConst.cs
Normal file
@@ -0,0 +1,15 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Yi.Framework.Common.Const
|
||||
{
|
||||
public class RabbitConst
|
||||
{
|
||||
private const string prefix = "Yi.Framework.";
|
||||
public const string SMS_Exchange = prefix+"SMS.Exchange";
|
||||
public const string SMS_Queue_Send = prefix+ "SMS.Queue.Send";
|
||||
}
|
||||
}
|
||||
43
Yi.Framework.Net6/Yi.Framework.Common/Const/RedisConst.cs
Normal file
@@ -0,0 +1,43 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Yi.Framework.Common.Const
|
||||
{
|
||||
public class RedisConst
|
||||
{
|
||||
/// <summary>
|
||||
/// 前缀
|
||||
/// </summary>
|
||||
public const string key = "YiFramework:data";
|
||||
|
||||
public const string keyCode = "YiFramework:code";
|
||||
///// <summary>
|
||||
///// 初始化角色名
|
||||
///// </summary>
|
||||
//public const string InitRole_key = nameof(InitRole_key);
|
||||
|
||||
///// <summary>
|
||||
///// 标题名
|
||||
///// </summary>
|
||||
//public const string Title_key = nameof(Title_key);
|
||||
|
||||
///// <summary>
|
||||
///// 图片列表名
|
||||
///// </summary>
|
||||
//public const string ImageList_key = nameof(ImageList_key);
|
||||
|
||||
//public static Dictionary<string, string> stringData = new Dictionary<string, string>()
|
||||
//{
|
||||
// {prefix+nameof(InitRole_key), "普通用户"},
|
||||
// {prefix+nameof(Title_key), "YiFramework"},
|
||||
//};
|
||||
|
||||
//public static Dictionary<string, List<string>> listData = new Dictionary<string, List<string>>()
|
||||
//{
|
||||
// {prefix+nameof(ImageList_key), new List<string>(){"图片地址1", "图片地址2", "图片地址3", "图片地址4" } }
|
||||
//};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Yi.Framework.Common.Helper
|
||||
{
|
||||
public class AssemblyHelper
|
||||
{
|
||||
public static List<Type> GetClass(string assemblyFile, string className = null, string spaceName=null)
|
||||
{
|
||||
Assembly assembly = Assembly.Load(assemblyFile);
|
||||
return assembly.GetTypes().Where(m => m.IsClass
|
||||
&& className == null?true:m.Name==className
|
||||
&& spaceName == null ? true :m.Namespace == spaceName
|
||||
).ToList();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
101
Yi.Framework.Net6/Yi.Framework.Common/Helper/Base32Helper.cs
Normal file
@@ -0,0 +1,101 @@
|
||||
using System;
|
||||
using System.Text;
|
||||
|
||||
namespace Yi.Framework.Common.Helper
|
||||
{
|
||||
public sealed class Base32Helper
|
||||
{
|
||||
|
||||
// the valid chars for the encoding
|
||||
private static string ValidChars = "QAZ2WSX3" + "EDC4RFV5" + "TGB6YHN7" + "UJM8K9LP";
|
||||
|
||||
/// <summary>
|
||||
/// Converts an array of bytes to a Base32-k string.
|
||||
/// </summary>
|
||||
public static string ToString(byte[] bytes)
|
||||
{
|
||||
StringBuilder sb = new StringBuilder(); // holds the base32 chars
|
||||
byte index;
|
||||
int hi = 5;
|
||||
int currentByte = 0;
|
||||
|
||||
while (currentByte < bytes.Length)
|
||||
{
|
||||
// do we need to use the next byte?
|
||||
if (hi > 8)
|
||||
{
|
||||
// get the last piece from the current byte, shift it to the right
|
||||
// and increment the byte counter
|
||||
index = (byte)(bytes[currentByte++] >> (hi - 5));
|
||||
if (currentByte != bytes.Length)
|
||||
{
|
||||
// if we are not at the end, get the first piece from
|
||||
// the next byte, clear it and shift it to the left
|
||||
index = (byte)(((byte)(bytes[currentByte] << (16 - hi)) >> 3) | index);
|
||||
}
|
||||
|
||||
hi -= 3;
|
||||
}
|
||||
else if (hi == 8)
|
||||
{
|
||||
index = (byte)(bytes[currentByte++] >> 3);
|
||||
hi -= 3;
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
// simply get the stuff from the current byte
|
||||
index = (byte)((byte)(bytes[currentByte] << (8 - hi)) >> 3);
|
||||
hi += 5;
|
||||
}
|
||||
|
||||
sb.Append(ValidChars[index]);
|
||||
}
|
||||
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Converts a Base32-k string into an array of bytes.
|
||||
/// </summary>
|
||||
/// <exception cref="System.ArgumentException">
|
||||
/// Input string <paramref name="s">s</paramref> contains invalid Base32-k characters.
|
||||
/// </exception>
|
||||
public static byte[] FromBase32String(string str)
|
||||
{
|
||||
int numBytes = str.Length * 5 / 8;
|
||||
byte[] bytes = new Byte[numBytes];
|
||||
|
||||
// all UPPERCASE chars
|
||||
str = str.ToUpper();
|
||||
|
||||
int bit_buffer;
|
||||
int currentCharIndex;
|
||||
int bits_in_buffer;
|
||||
|
||||
if (str.Length < 3)
|
||||
{
|
||||
bytes[0] = (byte)(ValidChars.IndexOf(str[0]) | ValidChars.IndexOf(str[1]) << 5);
|
||||
return bytes;
|
||||
}
|
||||
|
||||
bit_buffer = (ValidChars.IndexOf(str[0]) | ValidChars.IndexOf(str[1]) << 5);
|
||||
bits_in_buffer = 10;
|
||||
currentCharIndex = 2;
|
||||
for (int i = 0; i < bytes.Length; i++)
|
||||
{
|
||||
bytes[i] = (byte)bit_buffer;
|
||||
bit_buffer >>= 8;
|
||||
bits_in_buffer -= 8;
|
||||
while (bits_in_buffer < 8 && currentCharIndex < str.Length)
|
||||
{
|
||||
bit_buffer |= ValidChars.IndexOf(str[currentCharIndex++]) << bits_in_buffer;
|
||||
bits_in_buffer += 5;
|
||||
}
|
||||
}
|
||||
|
||||
return bytes;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
using System;
|
||||
|
||||
namespace Yi.Framework.Common.Helper
|
||||
{
|
||||
public static class ConsoleHelper
|
||||
{
|
||||
public static void WriteColorLine(string str, ConsoleColor color)
|
||||
{
|
||||
ConsoleColor currentForeColor = Console.ForegroundColor;
|
||||
Console.ForegroundColor = color;
|
||||
Console.WriteLine(str);
|
||||
Console.ForegroundColor = currentForeColor;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 打印错误信息
|
||||
/// </summary>
|
||||
/// <param name="str">待打印的字符串</param>
|
||||
/// <param name="color">想要打印的颜色</param>
|
||||
public static void WriteErrorLine(this string str, ConsoleColor color = ConsoleColor.Red)
|
||||
{
|
||||
WriteColorLine(str, color);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 打印警告信息
|
||||
/// </summary>
|
||||
/// <param name="str">待打印的字符串</param>
|
||||
/// <param name="color">想要打印的颜色</param>
|
||||
public static void WriteWarningLine(this string str, ConsoleColor color = ConsoleColor.Yellow)
|
||||
{
|
||||
WriteColorLine(str, color);
|
||||
}
|
||||
/// <summary>
|
||||
/// 打印正常信息
|
||||
/// </summary>
|
||||
/// <param name="str">待打印的字符串</param>
|
||||
/// <param name="color">想要打印的颜色</param>
|
||||
public static void WriteInfoLine(this string str, ConsoleColor color = ConsoleColor.White)
|
||||
{
|
||||
WriteColorLine(str, color);
|
||||
}
|
||||
/// <summary>
|
||||
/// 打印成功的信息
|
||||
/// </summary>
|
||||
/// <param name="str">待打印的字符串</param>
|
||||
/// <param name="color">想要打印的颜色</param>
|
||||
public static void WriteSuccessLine(this string str, ConsoleColor color = ConsoleColor.Green)
|
||||
{
|
||||
WriteColorLine(str, color);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
58
Yi.Framework.Net6/Yi.Framework.Common/Helper/DateHelper.cs
Normal file
@@ -0,0 +1,58 @@
|
||||
using System;
|
||||
|
||||
namespace Yi.Framework.Common.Helper
|
||||
{
|
||||
public class DateHelper
|
||||
{
|
||||
public static DateTime StampToDateTime(string time)
|
||||
{
|
||||
time = time.Substring(0, 10);
|
||||
double timestamp = Convert.ToInt64(time);
|
||||
System.DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);
|
||||
dateTime = dateTime.AddSeconds(timestamp).ToLocalTime();
|
||||
return dateTime;
|
||||
}
|
||||
|
||||
public static string TimeSubTract(DateTime time1,DateTime time2)
|
||||
{
|
||||
TimeSpan subTract = time1.Subtract(time2);
|
||||
return $"{subTract.Days} 天 {subTract.Hours} 时 {subTract.Minutes} 分 ";
|
||||
}
|
||||
/// <summary>
|
||||
/// 时间戳转本地时间-时间戳精确到秒
|
||||
/// </summary>
|
||||
public static DateTime ToLocalTimeDateBySeconds(long unix)
|
||||
{
|
||||
var dto = DateTimeOffset.FromUnixTimeSeconds(unix);
|
||||
return dto.ToLocalTime().DateTime;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 时间转时间戳Unix-时间戳精确到秒
|
||||
/// </summary>
|
||||
public static long ToUnixTimestampBySeconds(DateTime dt)
|
||||
{
|
||||
DateTimeOffset dto = new DateTimeOffset(dt);
|
||||
return dto.ToUnixTimeSeconds();
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 时间戳转本地时间-时间戳精确到毫秒
|
||||
/// </summary>
|
||||
public static DateTime ToLocalTimeDateByMilliseconds(long unix)
|
||||
{
|
||||
var dto = DateTimeOffset.FromUnixTimeMilliseconds(unix);
|
||||
return dto.ToLocalTime().DateTime;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 时间转时间戳Unix-时间戳精确到毫秒
|
||||
/// </summary>
|
||||
public static long ToUnixTimestampByMilliseconds(DateTime dt)
|
||||
{
|
||||
DateTimeOffset dto = new DateTimeOffset(dt);
|
||||
return dto.ToUnixTimeMilliseconds();
|
||||
}
|
||||
}
|
||||
}
|
||||
125
Yi.Framework.Net6/Yi.Framework.Common/Helper/EmailHelper.cs
Normal file
@@ -0,0 +1,125 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Net.Mail;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
|
||||
namespace Yi.Framework.Common.Helper
|
||||
{
|
||||
public class EmailHelper
|
||||
{
|
||||
public static string fromMail { get; set; }
|
||||
public static string pwdMail { get; set; }
|
||||
public static string senderMail { get; set; }
|
||||
public static string subjectMail { get; set; }
|
||||
public static void Init(string fromMail,string pwdMail,string senderMail, string subjectMail)
|
||||
{
|
||||
EmailHelper.fromMail = fromMail;
|
||||
EmailHelper.pwdMail = pwdMail;
|
||||
EmailHelper.senderMail = senderMail;
|
||||
EmailHelper.subjectMail = subjectMail;
|
||||
}
|
||||
|
||||
public static bool sendMail(string body, string toMail)
|
||||
{
|
||||
try
|
||||
{
|
||||
|
||||
//string fromMail = "454313500@qq.com";
|
||||
//string pwdMail = "yvjioburildgbhdf";
|
||||
MailMessage message = new MailMessage();
|
||||
//设置发件人,发件人需要与设置的邮件发送服务器的邮箱一致
|
||||
System.Net.Mail.MailAddress fromAddr = new System.Net.Mail.MailAddress(fromMail, EmailHelper.senderMail);
|
||||
message.From = fromAddr;
|
||||
|
||||
//设置收件人,可添加多个,添加方法与下面的一样
|
||||
message.To.Add(toMail);
|
||||
|
||||
|
||||
//设置邮件标题
|
||||
message.Subject = EmailHelper.subjectMail;
|
||||
|
||||
//设置邮件内容
|
||||
message.Body = body;
|
||||
|
||||
//设置邮件发送服务器,服务器根据你使用的邮箱而不同,可以到相应的 邮箱管理后台查看,下面是QQ的
|
||||
System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient("smtp.qq.com", 25)
|
||||
;
|
||||
//设置发送人的邮箱账号和密码,POP3/SMTP服务要开启, 密码要是POP3/SMTP等服务的授权码
|
||||
client.Credentials = new System.Net.NetworkCredential(fromMail, pwdMail);//vtirsfsthwuadjfe fhszmpegwoqnecja
|
||||
|
||||
//启用ssl,也就是安全发送
|
||||
client.EnableSsl = true;
|
||||
|
||||
//发送邮件
|
||||
client.Send(message);
|
||||
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static void 接受邮件()
|
||||
{
|
||||
using (TcpClient client = new TcpClient("pop.qq.com", 110))
|
||||
using (NetworkStream n = client.GetStream())
|
||||
{
|
||||
GetEmail.ReadLine(n); // Read the welcome message.
|
||||
GetEmail.SendCommand(n, "USER 1040079213@qq.com");
|
||||
GetEmail.SendCommand(n, "PASS odfaizoqdiupbfgi");
|
||||
GetEmail.SendCommand(n, "LIST"); // Retrieve message IDs
|
||||
List<int> messageIDs = new List<int>();
|
||||
while (true)
|
||||
{
|
||||
string line = GetEmail.ReadLine(n); // e.g., "11876"
|
||||
if (line == ".") break;
|
||||
messageIDs.Add(int.Parse(line.Split(' ')[0])); // Message ID
|
||||
}
|
||||
foreach (int id in messageIDs) // Retrieve each message.
|
||||
{
|
||||
GetEmail.SendCommand(n, "RETR " + id);
|
||||
string randomFile = Guid.NewGuid().ToString() + ".eml";
|
||||
using (StreamWriter writer = File.CreateText(randomFile))
|
||||
while (true)
|
||||
{
|
||||
string line = GetEmail.ReadLine(n); // Read next line of message.
|
||||
if (line == ".") break; // Single dot = end of message.
|
||||
if (line == "..") line = "."; // "Escape out" double dot.
|
||||
writer.WriteLine(line); // Write to output file.
|
||||
}
|
||||
GetEmail.SendCommand(n, "DELE " + id); // Delete message off server.
|
||||
}
|
||||
GetEmail.SendCommand(n, "QUIT");
|
||||
}
|
||||
}
|
||||
}
|
||||
//接受邮件pop
|
||||
public class GetEmail
|
||||
{
|
||||
public static void SendCommand(Stream stream, string line)
|
||||
{
|
||||
byte[] data = Encoding.UTF8.GetBytes(line + "\r\n");
|
||||
stream.Write(data, 0, data.Length);
|
||||
string response = ReadLine(stream);
|
||||
if (!response.StartsWith("+OK"))
|
||||
throw new Exception("POP Error: " + response);
|
||||
}
|
||||
public static string ReadLine(Stream s)
|
||||
{
|
||||
List<byte> lineBuffer = new List<byte>();
|
||||
while (true)
|
||||
{
|
||||
int b = s.ReadByte();
|
||||
if (b == 10 || b < 0) break;
|
||||
if (b != 13) lineBuffer.Add((byte)b);
|
||||
}
|
||||
return Encoding.UTF8.GetString(lineBuffer.ToArray());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
60
Yi.Framework.Net6/Yi.Framework.Common/Helper/ExcelHelper.cs
Normal file
@@ -0,0 +1,60 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using OfficeOpenXml;
|
||||
|
||||
namespace Yi.Framework.Common.Helper
|
||||
{
|
||||
public class ExcelHelper
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="dataList">数据</param>
|
||||
/// <param name="headers">表头</param>
|
||||
/// <returns></returns>
|
||||
public static string CreateExcelFromList<T>(List<T> dataList, List<string> headers,string evn)
|
||||
{
|
||||
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
|
||||
string sWebRootFolder = Path.Combine($"{evn}", "wwwroot/Excel");//如果用浏览器url下载的方式 存放excel的文件夹一定要建在网站首页的同级目录下!!!
|
||||
if (!Directory.Exists(sWebRootFolder))
|
||||
{
|
||||
Directory.CreateDirectory(sWebRootFolder);
|
||||
}
|
||||
string sFileName = $@"Excel_{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx";
|
||||
var path = Path.Combine(sWebRootFolder, sFileName);
|
||||
FileInfo file = new FileInfo(path);
|
||||
if (file.Exists)
|
||||
{
|
||||
file.Delete();
|
||||
file = new FileInfo(path);
|
||||
}
|
||||
using (ExcelPackage package = new(file))
|
||||
{
|
||||
//创建sheet
|
||||
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("sheet1");
|
||||
worksheet.Cells.LoadFromCollection(dataList, true);
|
||||
//表头字段
|
||||
for (int i = 0; i < headers.Count; i++)
|
||||
{
|
||||
worksheet.Cells[1, i + 1].Value = headers[i];
|
||||
}
|
||||
for (int i = 0; i < headers.Count + 1; i++)
|
||||
{//删除不需要的列
|
||||
string aa = worksheet.Cells[1, i + 1].Value.ToString();
|
||||
if (aa == "总行数")
|
||||
{
|
||||
worksheet.DeleteColumn(i + 1);
|
||||
}
|
||||
}
|
||||
package.Save();
|
||||
}
|
||||
//return path;//这是返回文件的方式
|
||||
return sFileName; //如果用浏览器url下载的方式 这里直接返回生成的文件名就可以了
|
||||
}
|
||||
}
|
||||
}
|
||||
395
Yi.Framework.Net6/Yi.Framework.Common/Helper/FileHelper.cs
Normal file
@@ -0,0 +1,395 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Yi.Framework.Common.Helper
|
||||
{
|
||||
public class FileHelper : IDisposable
|
||||
{
|
||||
|
||||
private bool _alreadyDispose = false;
|
||||
|
||||
#region 构造函数
|
||||
public FileHelper()
|
||||
{
|
||||
//
|
||||
// TODO: 在此处添加构造函数逻辑
|
||||
//
|
||||
}
|
||||
~FileHelper()
|
||||
{
|
||||
Dispose(); ;
|
||||
}
|
||||
|
||||
protected virtual void Dispose(bool isDisposing)
|
||||
{
|
||||
if (_alreadyDispose) return;
|
||||
_alreadyDispose = true;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region IDisposable 成员
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Dispose(true);
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 取得文件后缀名
|
||||
/****************************************
|
||||
* 函数名称:GetPostfixStr
|
||||
* 功能说明:取得文件后缀名
|
||||
* 参 数:filename:文件名称
|
||||
* 调用示列:
|
||||
* string filename = "aaa.aspx";
|
||||
* string s = EC.FileObj.GetPostfixStr(filename);
|
||||
*****************************************/
|
||||
/// <summary>
|
||||
/// 取后缀名
|
||||
/// </summary>
|
||||
/// <param name="filename">文件名</param>
|
||||
/// <returns>.gif|.html格式</returns>
|
||||
public static string GetPostfixStr(string filename)
|
||||
{
|
||||
int start = filename.LastIndexOf(".");
|
||||
int length = filename.Length;
|
||||
string postfix = filename.Substring(start, length - start);
|
||||
return postfix;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 根据文件大小获取指定前缀的可用文件名
|
||||
/// <summary>
|
||||
/// 根据文件大小获取指定前缀的可用文件名
|
||||
/// </summary>
|
||||
/// <param name="folderPath">文件夹</param>
|
||||
/// <param name="prefix">文件前缀</param>
|
||||
/// <param name="size">文件大小(1m)</param>
|
||||
/// <param name="ext">文件后缀(.log)</param>
|
||||
/// <returns>可用文件名</returns>
|
||||
//public static string GetAvailableFileWithPrefixOrderSize(string folderPath, string prefix, int size = 1 * 1024 * 1024, string ext = ".log")
|
||||
//{
|
||||
// var allFiles = new DirectoryInfo(folderPath);
|
||||
// var selectFiles = allFiles.GetFiles().Where(fi => fi.Name.ToLower().Contains(prefix.ToLower()) && fi.Extension.ToLower() == ext.ToLower() && fi.Length < size).OrderByDescending(d=>d.Name).ToList();
|
||||
|
||||
// if (selectFiles.Count > 0)
|
||||
// {
|
||||
// return selectFiles.FirstOrDefault().FullName;
|
||||
// }
|
||||
|
||||
// return Path.Combine(folderPath, $@"{prefix}_{DateTime.Now.DateToTimeStamp()}.log");
|
||||
//}
|
||||
//public static string GetAvailableFileNameWithPrefixOrderSize(string _contentRoot, string prefix, int size = 1 * 1024 * 1024, string ext = ".log")
|
||||
//{
|
||||
// var folderPath = Path.Combine(_contentRoot, "Log");
|
||||
// if (!Directory.Exists(folderPath))
|
||||
// {
|
||||
// Directory.CreateDirectory(folderPath);
|
||||
// }
|
||||
|
||||
// var allFiles = new DirectoryInfo(folderPath);
|
||||
// var selectFiles = allFiles.GetFiles().Where(fi => fi.Name.ToLower().Contains(prefix.ToLower()) && fi.Extension.ToLower() == ext.ToLower() && fi.Length < size).OrderByDescending(d => d.Name).ToList();
|
||||
|
||||
// if (selectFiles.Count > 0)
|
||||
// {
|
||||
// return selectFiles.FirstOrDefault().Name.Replace(".log","");
|
||||
// }
|
||||
|
||||
// return $@"{prefix}_{DateTime.Now.DateToTimeStamp()}";
|
||||
//}
|
||||
#endregion
|
||||
|
||||
#region 写文件
|
||||
/****************************************
|
||||
* 函数名称:WriteFile
|
||||
* 功能说明:写文件,会覆盖掉以前的内容
|
||||
* 参 数:Path:文件路径,Strings:文本内容
|
||||
* 调用示列:
|
||||
* string Path = Server.MapPath("Default2.aspx");
|
||||
* string Strings = "这是我写的内容啊";
|
||||
* EC.FileObj.WriteFile(Path,Strings);
|
||||
*****************************************/
|
||||
/// <summary>
|
||||
/// 写文件
|
||||
/// </summary>
|
||||
/// <param name="Path">文件路径</param>
|
||||
/// <param name="Strings">文件内容</param>
|
||||
public static void WriteFile(string Path, string Strings)
|
||||
{
|
||||
if (!File.Exists(Path))
|
||||
{
|
||||
FileStream f = File.Create(Path);
|
||||
f.Close();
|
||||
}
|
||||
StreamWriter f2 = new StreamWriter(Path, false, System.Text.Encoding.GetEncoding("gb2312"));
|
||||
f2.Write(Strings);
|
||||
f2.Close();
|
||||
f2.Dispose();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 写文件
|
||||
/// </summary>
|
||||
/// <param name="Path">文件路径</param>
|
||||
/// <param name="Strings">文件内容</param>
|
||||
/// <param name="encode">编码格式</param>
|
||||
public static void WriteFile(string Path, string Strings, Encoding encode)
|
||||
{
|
||||
if (!File.Exists(Path))
|
||||
{
|
||||
FileStream f = File.Create(Path);
|
||||
f.Close();
|
||||
}
|
||||
StreamWriter f2 = new StreamWriter(Path, false, encode);
|
||||
f2.Write(Strings);
|
||||
f2.Close();
|
||||
f2.Dispose();
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 读文件
|
||||
/****************************************
|
||||
* 函数名称:ReadFile
|
||||
* 功能说明:读取文本内容
|
||||
* 参 数:Path:文件路径
|
||||
* 调用示列:
|
||||
* string Path = Server.MapPath("Default2.aspx");
|
||||
* string s = EC.FileObj.ReadFile(Path);
|
||||
*****************************************/
|
||||
/// <summary>
|
||||
/// 读文件
|
||||
/// </summary>
|
||||
/// <param name="Path">文件路径</param>
|
||||
/// <returns></returns>
|
||||
public static string ReadFile(string Path)
|
||||
{
|
||||
string s = "";
|
||||
if (!File.Exists(Path))
|
||||
s = "不存在相应的目录";
|
||||
else
|
||||
{
|
||||
StreamReader f2 = new StreamReader(Path, System.Text.Encoding.GetEncoding("gb2312"));
|
||||
s = f2.ReadToEnd();
|
||||
f2.Close();
|
||||
f2.Dispose();
|
||||
}
|
||||
|
||||
return s;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 读文件
|
||||
/// </summary>
|
||||
/// <param name="Path">文件路径</param>
|
||||
/// <param name="encode">编码格式</param>
|
||||
/// <returns></returns>
|
||||
public static string ReadFile(string Path, Encoding encode)
|
||||
{
|
||||
string s = "";
|
||||
if (!File.Exists(Path))
|
||||
s = "不存在相应的目录";
|
||||
else
|
||||
{
|
||||
StreamReader f2 = new StreamReader(Path, encode);
|
||||
s = f2.ReadToEnd();
|
||||
f2.Close();
|
||||
f2.Dispose();
|
||||
}
|
||||
|
||||
return s;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 追加文件
|
||||
/****************************************
|
||||
* 函数名称:FileAdd
|
||||
* 功能说明:追加文件内容
|
||||
* 参 数:Path:文件路径,strings:内容
|
||||
* 调用示列:
|
||||
* string Path = Server.MapPath("Default2.aspx");
|
||||
* string Strings = "新追加内容";
|
||||
* EC.FileObj.FileAdd(Path, Strings);
|
||||
*****************************************/
|
||||
/// <summary>
|
||||
/// 追加文件
|
||||
/// </summary>
|
||||
/// <param name="Path">文件路径</param>
|
||||
/// <param name="strings">内容</param>
|
||||
public static void FileAdd(string Path, string strings)
|
||||
{
|
||||
StreamWriter sw = File.AppendText(Path);
|
||||
sw.Write(strings);
|
||||
sw.Flush();
|
||||
sw.Close();
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 拷贝文件
|
||||
/****************************************
|
||||
* 函数名称:FileCoppy
|
||||
* 功能说明:拷贝文件
|
||||
* 参 数:OrignFile:原始文件,NewFile:新文件路径
|
||||
* 调用示列:
|
||||
* string orignFile = Server.MapPath("Default2.aspx");
|
||||
* string NewFile = Server.MapPath("Default3.aspx");
|
||||
* EC.FileObj.FileCoppy(OrignFile, NewFile);
|
||||
*****************************************/
|
||||
/// <summary>
|
||||
/// 拷贝文件
|
||||
/// </summary>
|
||||
/// <param name="OrignFile">原始文件</param>
|
||||
/// <param name="NewFile">新文件路径</param>
|
||||
public static void FileCoppy(string orignFile, string NewFile)
|
||||
{
|
||||
File.Copy(orignFile, NewFile, true);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 删除文件
|
||||
/****************************************
|
||||
* 函数名称:FileDel
|
||||
* 功能说明:删除文件
|
||||
* 参 数:Path:文件路径
|
||||
* 调用示列:
|
||||
* string Path = Server.MapPath("Default3.aspx");
|
||||
* EC.FileObj.FileDel(Path);
|
||||
*****************************************/
|
||||
/// <summary>
|
||||
/// 删除文件
|
||||
/// </summary>
|
||||
/// <param name="Path">路径</param>
|
||||
public static void FileDel(string Path)
|
||||
{
|
||||
File.Delete(Path);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 移动文件
|
||||
/****************************************
|
||||
* 函数名称:FileMove
|
||||
* 功能说明:移动文件
|
||||
* 参 数:OrignFile:原始路径,NewFile:新文件路径
|
||||
* 调用示列:
|
||||
* string orignFile = Server.MapPath("../说明.txt");
|
||||
* string NewFile = Server.MapPath("http://www.cnblogs.com/说明.txt");
|
||||
* EC.FileObj.FileMove(OrignFile, NewFile);
|
||||
*****************************************/
|
||||
/// <summary>
|
||||
/// 移动文件
|
||||
/// </summary>
|
||||
/// <param name="OrignFile">原始路径</param>
|
||||
/// <param name="NewFile">新路径</param>
|
||||
public static void FileMove(string orignFile, string NewFile)
|
||||
{
|
||||
File.Move(orignFile, NewFile);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 在当前目录下创建目录
|
||||
/****************************************
|
||||
* 函数名称:FolderCreate
|
||||
* 功能说明:在当前目录下创建目录
|
||||
* 参 数:OrignFolder:当前目录,NewFloder:新目录
|
||||
* 调用示列:
|
||||
* string orignFolder = Server.MapPath("test/");
|
||||
* string NewFloder = "new";
|
||||
* EC.FileObj.FolderCreate(OrignFolder, NewFloder);
|
||||
*****************************************/
|
||||
/// <summary>
|
||||
/// 在当前目录下创建目录
|
||||
/// </summary>
|
||||
/// <param name="OrignFolder">当前目录</param>
|
||||
/// <param name="NewFloder">新目录</param>
|
||||
public static void FolderCreate(string orignFolder, string NewFloder)
|
||||
{
|
||||
Directory.SetCurrentDirectory(orignFolder);
|
||||
Directory.CreateDirectory(NewFloder);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 递归删除文件夹目录及文件
|
||||
/****************************************
|
||||
* 函数名称:DeleteFolder
|
||||
* 功能说明:递归删除文件夹目录及文件
|
||||
* 参 数:dir:文件夹路径
|
||||
* 调用示列:
|
||||
* string dir = Server.MapPath("test/");
|
||||
* EC.FileObj.DeleteFolder(dir);
|
||||
*****************************************/
|
||||
/// <summary>
|
||||
/// 递归删除文件夹目录及文件
|
||||
/// </summary>
|
||||
/// <param name="dir"></param>
|
||||
/// <returns></returns>
|
||||
public static void DeleteFolder(string dir)
|
||||
{
|
||||
if (Directory.Exists(dir)) //如果存在这个文件夹删除之
|
||||
{
|
||||
foreach (string d in Directory.GetFileSystemEntries(dir))
|
||||
{
|
||||
if (File.Exists(d))
|
||||
File.Delete(d); //直接删除其中的文件
|
||||
else
|
||||
DeleteFolder(d); //递归删除子文件夹
|
||||
}
|
||||
Directory.Delete(dir); //删除已空文件夹
|
||||
}
|
||||
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 将指定文件夹下面的所有内容copy到目标文件夹下面 果目标文件夹为只读属性就会报错。
|
||||
/****************************************
|
||||
* 函数名称:CopyDir
|
||||
* 功能说明:将指定文件夹下面的所有内容copy到目标文件夹下面 果目标文件夹为只读属性就会报错。
|
||||
* 参 数:srcPath:原始路径,aimPath:目标文件夹
|
||||
* 调用示列:
|
||||
* string srcPath = Server.MapPath("test/");
|
||||
* string aimPath = Server.MapPath("test1/");
|
||||
* EC.FileObj.CopyDir(srcPath,aimPath);
|
||||
*****************************************/
|
||||
/// <summary>
|
||||
/// 指定文件夹下面的所有内容copy到目标文件夹下面
|
||||
/// </summary>
|
||||
/// <param name="srcPath">原始路径</param>
|
||||
/// <param name="aimPath">目标文件夹</param>
|
||||
public static void CopyDir(string srcPath, string aimPath)
|
||||
{
|
||||
try
|
||||
{
|
||||
// 检查目标目录是否以目录分割字符结束如果不是则添加之
|
||||
if (aimPath[aimPath.Length - 1] != Path.DirectorySeparatorChar)
|
||||
aimPath += Path.DirectorySeparatorChar;
|
||||
// 判断目标目录是否存在如果不存在则新建之
|
||||
if (!Directory.Exists(aimPath))
|
||||
Directory.CreateDirectory(aimPath);
|
||||
// 得到源目录的文件列表,该里面是包含文件以及目录路径的一个数组
|
||||
//如果你指向copy目标文件下面的文件而不包含目录请使用下面的方法
|
||||
//string[] fileList = Directory.GetFiles(srcPath);
|
||||
string[] fileList = Directory.GetFileSystemEntries(srcPath);
|
||||
//遍历所有的文件和目录
|
||||
foreach (string file in fileList)
|
||||
{
|
||||
//先当作目录处理如果存在这个目录就递归Copy该目录下面的文件
|
||||
|
||||
if (Directory.Exists(file))
|
||||
CopyDir(file, aimPath + Path.GetFileName(file));
|
||||
//否则直接Copy文件
|
||||
else
|
||||
File.Copy(file, aimPath + Path.GetFileName(file), true);
|
||||
}
|
||||
|
||||
}
|
||||
catch (Exception ee)
|
||||
{
|
||||
throw new Exception(ee.ToString());
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
24
Yi.Framework.Net6/Yi.Framework.Common/Helper/HtmlHelper.cs
Normal file
@@ -0,0 +1,24 @@
|
||||
namespace Yi.Framework.Common.Helper
|
||||
{
|
||||
public static class HtmlHelper
|
||||
{
|
||||
#region 去除富文本中的HTML标签
|
||||
/// <summary>
|
||||
/// 去除富文本中的HTML标签
|
||||
/// </summary>
|
||||
/// <param name="html"></param>
|
||||
/// <param name="length"></param>
|
||||
/// <returns></returns>
|
||||
public static string ReplaceHtmlTag(string html, int length = 0)
|
||||
{
|
||||
string strText = System.Text.RegularExpressions.Regex.Replace(html, "<[^>]+>", "");
|
||||
strText = System.Text.RegularExpressions.Regex.Replace(strText, "&[^;]+;", "");
|
||||
|
||||
if (length > 0 && strText.Length > length)
|
||||
return strText.Substring(0, length);
|
||||
|
||||
return strText;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
76
Yi.Framework.Net6/Yi.Framework.Common/Helper/HttpHelper.cs
Normal file
@@ -0,0 +1,76 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Yi.Framework.Common.Helper
|
||||
{
|
||||
public static class HttpHelper
|
||||
{
|
||||
public static string HttpGet(string Url, string postDataStr="")
|
||||
{
|
||||
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr);
|
||||
request.Method = "GET";
|
||||
request.ContentType = "text/html;charset=UTF-8";
|
||||
|
||||
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
|
||||
Stream myResponseStream = response.GetResponseStream();
|
||||
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
|
||||
string retString = myStreamReader.ReadToEnd();
|
||||
myStreamReader.Close();
|
||||
myResponseStream.Close();
|
||||
|
||||
return retString;
|
||||
}
|
||||
|
||||
public static bool HttpIOGet(string Url, string file, string postDataStr="")
|
||||
{
|
||||
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr);
|
||||
request.Method = "GET";
|
||||
request.ContentType = "text/html;charset=UTF-8";
|
||||
|
||||
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
|
||||
Stream myResponseStream = response.GetResponseStream();
|
||||
FileStream writer = new FileStream(file, FileMode.OpenOrCreate, FileAccess.Write);
|
||||
byte[] buffer = new byte[1024];
|
||||
int c;
|
||||
while ((c = myResponseStream.Read(buffer, 0, buffer.Length)) > 0)
|
||||
{
|
||||
writer.Write(buffer, 0, c);
|
||||
}
|
||||
writer.Close();
|
||||
myResponseStream.Close();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public static string HttpPost(string Url, string postDataStr="")
|
||||
{
|
||||
CookieContainer cookie = new CookieContainer();
|
||||
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
|
||||
request.Method = "POST";
|
||||
request.ContentType = "application/x-www-form-urlencoded";
|
||||
request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr);
|
||||
request.CookieContainer = cookie;
|
||||
Stream myRequestStream = request.GetRequestStream();
|
||||
StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));
|
||||
myStreamWriter.Write(postDataStr);
|
||||
myStreamWriter.Close();
|
||||
|
||||
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
|
||||
|
||||
response.Cookies = cookie.GetCookies(response.ResponseUri);
|
||||
Stream myResponseStream = response.GetResponseStream();
|
||||
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
|
||||
string retString = myStreamReader.ReadToEnd();
|
||||
myStreamReader.Close();
|
||||
myResponseStream.Close();
|
||||
|
||||
return retString;
|
||||
}
|
||||
}
|
||||
}
|
||||
51
Yi.Framework.Net6/Yi.Framework.Common/Helper/IpHelper.cs
Normal file
@@ -0,0 +1,51 @@
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.NetworkInformation;
|
||||
using System.Net.Sockets;
|
||||
|
||||
namespace Yi.Framework.Common.Helper
|
||||
{
|
||||
public class IpHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// 获取当前IP地址
|
||||
/// </summary>
|
||||
/// <param name="preferredNetworks"></param>
|
||||
/// <returns></returns>
|
||||
public static string GetCurrentIp(string preferredNetworks)
|
||||
{
|
||||
var instanceIp = "127.0.0.1";
|
||||
|
||||
try
|
||||
{
|
||||
// 获取可用网卡
|
||||
var nics = NetworkInterface.GetAllNetworkInterfaces()?.Where(network => network.OperationalStatus == OperationalStatus.Up);
|
||||
|
||||
// 获取所有可用网卡IP信息
|
||||
var ipCollection = nics?.Select(x => x.GetIPProperties())?.SelectMany(x => x.UnicastAddresses);
|
||||
|
||||
foreach (var ipadd in ipCollection)
|
||||
{
|
||||
if (!IPAddress.IsLoopback(ipadd.Address) && ipadd.Address.AddressFamily == AddressFamily.InterNetwork)
|
||||
{
|
||||
if (string.IsNullOrEmpty(preferredNetworks))
|
||||
{
|
||||
instanceIp = ipadd.Address.ToString();
|
||||
break;
|
||||
}
|
||||
|
||||
if (!ipadd.Address.ToString().StartsWith(preferredNetworks)) continue;
|
||||
instanceIp = ipadd.Address.ToString();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// ignored
|
||||
}
|
||||
|
||||
return instanceIp;
|
||||
}
|
||||
}
|
||||
}
|
||||
509
Yi.Framework.Net6/Yi.Framework.Common/Helper/JsonHelper.cs
Normal file
@@ -0,0 +1,509 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace Yi.Framework.Common.Helper
|
||||
{
|
||||
public class JsonHelper
|
||||
{
|
||||
|
||||
|
||||
public static string ObjToStr<T>(T obj)
|
||||
{
|
||||
return Newtonsoft.Json.JsonConvert.SerializeObject(obj);
|
||||
}
|
||||
|
||||
public static T StrToObj<T>(string str)
|
||||
{
|
||||
return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(str);
|
||||
}
|
||||
/// <summary>
|
||||
/// 转换对象为JSON格式数据
|
||||
/// </summary>
|
||||
/// <typeparam name="T">类</typeparam>
|
||||
/// <param name="obj">对象</param>
|
||||
/// <returns>字符格式的JSON数据</returns>
|
||||
public static string GetJSON<T>(object obj)
|
||||
{
|
||||
string result = String.Empty;
|
||||
try
|
||||
{
|
||||
JsonSerializer.Serialize("");
|
||||
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer =
|
||||
new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T));
|
||||
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
|
||||
{
|
||||
serializer.WriteObject(ms, obj);
|
||||
result = System.Text.Encoding.UTF8.GetString(ms.ToArray());
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
/// <summary>
|
||||
/// 转换List<T>的数据为JSON格式
|
||||
/// </summary>
|
||||
/// <typeparam name="T">类</typeparam>
|
||||
/// <param name="vals">列表值</param>
|
||||
/// <returns>JSON格式数据</returns>
|
||||
public string JSON<T>(List<T> vals)
|
||||
{
|
||||
System.Text.StringBuilder st = new System.Text.StringBuilder();
|
||||
try
|
||||
{
|
||||
System.Runtime.Serialization.Json.DataContractJsonSerializer s = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T));
|
||||
|
||||
foreach (T city in vals)
|
||||
{
|
||||
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
|
||||
{
|
||||
s.WriteObject(ms, city);
|
||||
st.Append(System.Text.Encoding.UTF8.GetString(ms.ToArray()));
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
}
|
||||
|
||||
return st.ToString();
|
||||
}
|
||||
/// <summary>
|
||||
/// JSON格式字符转换为T类型的对象
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="jsonStr"></param>
|
||||
/// <returns></returns>
|
||||
public static T ParseFormByJson<T>(string jsonStr)
|
||||
{
|
||||
T obj = Activator.CreateInstance<T>();
|
||||
using (System.IO.MemoryStream ms =
|
||||
new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(jsonStr)))
|
||||
{
|
||||
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer =
|
||||
new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T));
|
||||
return (T)serializer.ReadObject(ms);
|
||||
}
|
||||
}
|
||||
|
||||
public string JSON1<SendData>(List<SendData> vals)
|
||||
{
|
||||
System.Text.StringBuilder st = new System.Text.StringBuilder();
|
||||
try
|
||||
{
|
||||
System.Runtime.Serialization.Json.DataContractJsonSerializer s = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(SendData));
|
||||
|
||||
foreach (SendData city in vals)
|
||||
{
|
||||
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
|
||||
{
|
||||
s.WriteObject(ms, city);
|
||||
st.Append(System.Text.Encoding.UTF8.GetString(ms.ToArray()));
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
}
|
||||
|
||||
return st.ToString();
|
||||
}
|
||||
|
||||
private static bool IsJsonStart(ref string json)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(json))
|
||||
{
|
||||
json = json.Trim('\r', '\n', ' ');
|
||||
if (json.Length > 1)
|
||||
{
|
||||
char s = json[0];
|
||||
char e = json[json.Length - 1];
|
||||
return (s == '{' && e == '}') || (s == '[' && e == ']');
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
public static bool IsJson(string json)
|
||||
{
|
||||
int errIndex;
|
||||
return IsJson(json, out errIndex);
|
||||
}
|
||||
public static bool IsJson(string json, out int errIndex)
|
||||
{
|
||||
errIndex = 0;
|
||||
if (IsJsonStart(ref json))
|
||||
{
|
||||
CharState cs = new CharState();
|
||||
char c;
|
||||
for (int i = 0; i < json.Length; i++)
|
||||
{
|
||||
c = json[i];
|
||||
if (SetCharState(c, ref cs) && cs.childrenStart)//设置关键符号状态。
|
||||
{
|
||||
string item = json.Substring(i);
|
||||
int err;
|
||||
int length = GetValueLength(item, true, out err);
|
||||
cs.childrenStart = false;
|
||||
if (err > 0)
|
||||
{
|
||||
errIndex = i + err;
|
||||
return false;
|
||||
}
|
||||
i = i + length - 1;
|
||||
}
|
||||
if (cs.isError)
|
||||
{
|
||||
errIndex = i;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return !cs.arrayStart && !cs.jsonStart;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取值的长度(当Json值嵌套以"{"或"["开头时)
|
||||
/// </summary>
|
||||
private static int GetValueLength(string json, bool breakOnErr, out int errIndex)
|
||||
{
|
||||
errIndex = 0;
|
||||
int len = 0;
|
||||
if (!string.IsNullOrEmpty(json))
|
||||
{
|
||||
CharState cs = new CharState();
|
||||
char c;
|
||||
for (int i = 0; i < json.Length; i++)
|
||||
{
|
||||
c = json[i];
|
||||
if (!SetCharState(c, ref cs))//设置关键符号状态。
|
||||
{
|
||||
if (!cs.jsonStart && !cs.arrayStart)//json结束,又不是数组,则退出。
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
else if (cs.childrenStart)//正常字符,值状态下。
|
||||
{
|
||||
int length = GetValueLength(json.Substring(i), breakOnErr, out errIndex);//递归子值,返回一个长度。。。
|
||||
cs.childrenStart = false;
|
||||
cs.valueStart = 0;
|
||||
//cs.state = 0;
|
||||
i = i + length - 1;
|
||||
}
|
||||
if (breakOnErr && cs.isError)
|
||||
{
|
||||
errIndex = i;
|
||||
return i;
|
||||
}
|
||||
if (!cs.jsonStart && !cs.arrayStart)//记录当前结束位置。
|
||||
{
|
||||
len = i + 1;//长度比索引+1
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return len;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 设置字符状态(返回true则为关键词,返回false则当为普通字符处理)
|
||||
/// </summary>
|
||||
private static bool SetCharState(char c, ref CharState cs)
|
||||
{
|
||||
cs.CheckIsError(c);
|
||||
switch (c)
|
||||
{
|
||||
case '{'://[{ "[{A}]":[{"[{B}]":3,"m":"C"}]}]
|
||||
#region 大括号
|
||||
if (cs.keyStart <= 0 && cs.valueStart <= 0)
|
||||
{
|
||||
cs.keyStart = 0;
|
||||
cs.valueStart = 0;
|
||||
if (cs.jsonStart && cs.state == 1)
|
||||
{
|
||||
cs.childrenStart = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
cs.state = 0;
|
||||
}
|
||||
cs.jsonStart = true;//开始。
|
||||
return true;
|
||||
}
|
||||
#endregion
|
||||
break;
|
||||
case '}':
|
||||
#region 大括号结束
|
||||
if (cs.keyStart <= 0 && cs.valueStart < 2 && cs.jsonStart)
|
||||
{
|
||||
cs.jsonStart = false;//正常结束。
|
||||
cs.state = 0;
|
||||
cs.keyStart = 0;
|
||||
cs.valueStart = 0;
|
||||
cs.setDicValue = true;
|
||||
return true;
|
||||
}
|
||||
// cs.isError = !cs.jsonStart && cs.state == 0;
|
||||
#endregion
|
||||
break;
|
||||
case '[':
|
||||
#region 中括号开始
|
||||
if (!cs.jsonStart)
|
||||
{
|
||||
cs.arrayStart = true;
|
||||
return true;
|
||||
}
|
||||
else if (cs.jsonStart && cs.state == 1)
|
||||
{
|
||||
cs.childrenStart = true;
|
||||
return true;
|
||||
}
|
||||
#endregion
|
||||
break;
|
||||
case ']':
|
||||
#region 中括号结束
|
||||
if (cs.arrayStart && !cs.jsonStart && cs.keyStart <= 2 && cs.valueStart <= 0)//[{},333]//这样结束。
|
||||
{
|
||||
cs.keyStart = 0;
|
||||
cs.valueStart = 0;
|
||||
cs.arrayStart = false;
|
||||
return true;
|
||||
}
|
||||
#endregion
|
||||
break;
|
||||
case '"':
|
||||
case '\'':
|
||||
#region 引号
|
||||
if (cs.jsonStart || cs.arrayStart)
|
||||
{
|
||||
if (cs.state == 0)//key阶段,有可能是数组["aa",{}]
|
||||
{
|
||||
if (cs.keyStart <= 0)
|
||||
{
|
||||
cs.keyStart = (c == '"' ? 3 : 2);
|
||||
return true;
|
||||
}
|
||||
else if ((cs.keyStart == 2 && c == '\'') || (cs.keyStart == 3 && c == '"'))
|
||||
{
|
||||
if (!cs.escapeChar)
|
||||
{
|
||||
cs.keyStart = -1;
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
cs.escapeChar = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (cs.state == 1 && cs.jsonStart)//值阶段必须是Json开始了。
|
||||
{
|
||||
if (cs.valueStart <= 0)
|
||||
{
|
||||
cs.valueStart = (c == '"' ? 3 : 2);
|
||||
return true;
|
||||
}
|
||||
else if ((cs.valueStart == 2 && c == '\'') || (cs.valueStart == 3 && c == '"'))
|
||||
{
|
||||
if (!cs.escapeChar)
|
||||
{
|
||||
cs.valueStart = -1;
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
cs.escapeChar = false;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
break;
|
||||
case ':':
|
||||
#region 冒号
|
||||
if (cs.jsonStart && cs.keyStart < 2 && cs.valueStart < 2 && cs.state == 0)
|
||||
{
|
||||
if (cs.keyStart == 1)
|
||||
{
|
||||
cs.keyStart = -1;
|
||||
}
|
||||
cs.state = 1;
|
||||
return true;
|
||||
}
|
||||
// cs.isError = !cs.jsonStart || (cs.keyStart < 2 && cs.valueStart < 2 && cs.state == 1);
|
||||
#endregion
|
||||
break;
|
||||
case ',':
|
||||
#region 逗号 //["aa",{aa:12,}]
|
||||
|
||||
if (cs.jsonStart)
|
||||
{
|
||||
if (cs.keyStart < 2 && cs.valueStart < 2 && cs.state == 1)
|
||||
{
|
||||
cs.state = 0;
|
||||
cs.keyStart = 0;
|
||||
cs.valueStart = 0;
|
||||
//if (cs.valueStart == 1)
|
||||
//{
|
||||
// cs.valueStart = 0;
|
||||
//}
|
||||
cs.setDicValue = true;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
else if (cs.arrayStart && cs.keyStart <= 2)
|
||||
{
|
||||
cs.keyStart = 0;
|
||||
//if (cs.keyStart == 1)
|
||||
//{
|
||||
// cs.keyStart = -1;
|
||||
//}
|
||||
return true;
|
||||
}
|
||||
#endregion
|
||||
break;
|
||||
case ' ':
|
||||
case '\r':
|
||||
case '\n'://[ "a",\r\n{} ]
|
||||
case '\0':
|
||||
case '\t':
|
||||
if (cs.keyStart <= 0 && cs.valueStart <= 0) //cs.jsonStart &&
|
||||
{
|
||||
return true;//跳过空格。
|
||||
}
|
||||
break;
|
||||
default: //值开头。。
|
||||
if (c == '\\') //转义符号
|
||||
{
|
||||
if (cs.escapeChar)
|
||||
{
|
||||
cs.escapeChar = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
cs.escapeChar = true;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
cs.escapeChar = false;
|
||||
}
|
||||
if (cs.jsonStart || cs.arrayStart) // Json 或数组开始了。
|
||||
{
|
||||
if (cs.keyStart <= 0 && cs.state == 0)
|
||||
{
|
||||
cs.keyStart = 1;//无引号的
|
||||
}
|
||||
else if (cs.valueStart <= 0 && cs.state == 1 && cs.jsonStart)//只有Json开始才有值。
|
||||
{
|
||||
cs.valueStart = 1;//无引号的
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 字符状态
|
||||
/// </summary>
|
||||
public class CharState
|
||||
{
|
||||
internal bool jsonStart = false;//以 "{"开始了...
|
||||
internal bool setDicValue = false;// 可以设置字典值了。
|
||||
internal bool escapeChar = false;//以"\"转义符号开始了
|
||||
/// <summary>
|
||||
/// 数组开始【仅第一开头才算】,值嵌套的以【childrenStart】来标识。
|
||||
/// </summary>
|
||||
internal bool arrayStart = false;//以"[" 符号开始了
|
||||
internal bool childrenStart = false;//子级嵌套开始了。
|
||||
/// <summary>
|
||||
/// 【0 初始状态,或 遇到“,”逗号】;【1 遇到“:”冒号】
|
||||
/// </summary>
|
||||
internal int state = 0;
|
||||
|
||||
/// <summary>
|
||||
/// 【-1 取值结束】【0 未开始】【1 无引号开始】【2 单引号开始】【3 双引号开始】
|
||||
/// </summary>
|
||||
internal int keyStart = 0;
|
||||
/// <summary>
|
||||
/// 【-1 取值结束】【0 未开始】【1 无引号开始】【2 单引号开始】【3 双引号开始】
|
||||
/// </summary>
|
||||
internal int valueStart = 0;
|
||||
internal bool isError = false;//是否语法错误。
|
||||
|
||||
internal void CheckIsError(char c)//只当成一级处理(因为GetLength会递归到每一个子项处理)
|
||||
{
|
||||
if (keyStart > 1 || valueStart > 1)
|
||||
{
|
||||
return;
|
||||
}
|
||||
//示例 ["aa",{"bbbb":123,"fff","ddd"}]
|
||||
switch (c)
|
||||
{
|
||||
case '{'://[{ "[{A}]":[{"[{B}]":3,"m":"C"}]}]
|
||||
isError = jsonStart && state == 0;//重复开始错误 同时不是值处理。
|
||||
break;
|
||||
case '}':
|
||||
isError = !jsonStart || (keyStart != 0 && state == 0);//重复结束错误 或者 提前结束{"aa"}。正常的有{}
|
||||
break;
|
||||
case '[':
|
||||
isError = arrayStart && state == 0;//重复开始错误
|
||||
break;
|
||||
case ']':
|
||||
isError = !arrayStart || jsonStart;//重复开始错误 或者 Json 未结束
|
||||
break;
|
||||
case '"':
|
||||
case '\'':
|
||||
isError = !(jsonStart || arrayStart); //json 或数组开始。
|
||||
if (!isError)
|
||||
{
|
||||
//重复开始 [""",{"" "}]
|
||||
isError = (state == 0 && keyStart == -1) || (state == 1 && valueStart == -1);
|
||||
}
|
||||
if (!isError && arrayStart && !jsonStart && c == '\'')//['aa',{}]
|
||||
{
|
||||
isError = true;
|
||||
}
|
||||
break;
|
||||
case ':':
|
||||
isError = !jsonStart || state == 1;//重复出现。
|
||||
break;
|
||||
case ',':
|
||||
isError = !(jsonStart || arrayStart); //json 或数组开始。
|
||||
if (!isError)
|
||||
{
|
||||
if (jsonStart)
|
||||
{
|
||||
isError = state == 0 || (state == 1 && valueStart > 1);//重复出现。
|
||||
}
|
||||
else if (arrayStart)//["aa,] [,] [{},{}]
|
||||
{
|
||||
isError = keyStart == 0 && !setDicValue;
|
||||
}
|
||||
}
|
||||
break;
|
||||
case ' ':
|
||||
case '\r':
|
||||
case '\n'://[ "a",\r\n{} ]
|
||||
case '\0':
|
||||
case '\t':
|
||||
break;
|
||||
default: //值开头。。
|
||||
isError = (!jsonStart && !arrayStart) || (state == 0 && keyStart == -1) || (valueStart == -1 && state == 1);//
|
||||
break;
|
||||
}
|
||||
//if (isError)
|
||||
//{
|
||||
|
||||
//}
|
||||
}
|
||||
}
|
||||
}
|
||||
67
Yi.Framework.Net6/Yi.Framework.Common/Helper/MD5Hepler.cs
Normal file
@@ -0,0 +1,67 @@
|
||||
using System;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace Yi.Framework.Common.Helper
|
||||
{
|
||||
public class MD5Helper
|
||||
{
|
||||
/// <summary>
|
||||
/// 16位MD5加密
|
||||
/// </summary>
|
||||
/// <param name="password"></param>
|
||||
/// <returns></returns>
|
||||
public static string MD5Encrypt16(string password)
|
||||
{
|
||||
var md5 = new MD5CryptoServiceProvider();
|
||||
string t2 = BitConverter.ToString(md5.ComputeHash(Encoding.Default.GetBytes(password)), 4, 8);
|
||||
t2 = t2.Replace("-", string.Empty);
|
||||
return t2;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 32位MD5加密
|
||||
/// </summary>
|
||||
/// <param name="password"></param>
|
||||
/// <returns></returns>
|
||||
public static string MD5Encrypt32(string password = "")
|
||||
{
|
||||
string pwd = string.Empty;
|
||||
try
|
||||
{
|
||||
if (!string.IsNullOrEmpty(password) && !string.IsNullOrWhiteSpace(password))
|
||||
{
|
||||
MD5 md5 = MD5.Create(); //实例化一个md5对像
|
||||
// 加密后是一个字节类型的数组,这里要注意编码UTF8/Unicode等的选择
|
||||
byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(password));
|
||||
// 通过使用循环,将字节类型的数组转换为字符串,此字符串是常规字符格式化所得
|
||||
foreach (var item in s)
|
||||
{
|
||||
// 将得到的字符串使用十六进制类型格式。格式后的字符是小写的字母,如果使用大写(X)则格式后的字符是大写字符
|
||||
pwd = string.Concat(pwd, item.ToString("X2"));
|
||||
}
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
throw new Exception($"错误的 password 字符串:【{password}】");
|
||||
}
|
||||
return pwd;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 64位MD5加密
|
||||
/// </summary>
|
||||
/// <param name="password"></param>
|
||||
/// <returns></returns>
|
||||
public static string MD5Encrypt64(string password)
|
||||
{
|
||||
// 实例化一个md5对像
|
||||
// 加密后是一个字节类型的数组,这里要注意编码UTF8/Unicode等的选择
|
||||
MD5 md5 = MD5.Create();
|
||||
byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(password));
|
||||
return Convert.ToBase64String(s);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
244
Yi.Framework.Net6/Yi.Framework.Common/Helper/MimeHelper.cs
Normal file
@@ -0,0 +1,244 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Yi.Framework.Common.Helper
|
||||
{
|
||||
public static class MimeHelper
|
||||
{
|
||||
// 通过自己定义一个静态类
|
||||
// 将所有的Content Type都扔进去吧
|
||||
// 调用的时候直接调用静态方法即可。
|
||||
|
||||
private static Hashtable _mimeMappingTable;
|
||||
|
||||
private static void AddMimeMapping(string extension, string MimeType)
|
||||
{
|
||||
MimeHelper._mimeMappingTable.Add(extension, MimeType);
|
||||
}
|
||||
|
||||
public static string GetMimeMapping(string FileName)
|
||||
{
|
||||
string text = null;
|
||||
int num = FileName.LastIndexOf('.');
|
||||
if (0 < num && num > FileName.LastIndexOf('\\'))
|
||||
{
|
||||
text = (string)MimeHelper._mimeMappingTable[FileName.Substring(num)];
|
||||
}
|
||||
if (text == null)
|
||||
{
|
||||
text = (string)MimeHelper._mimeMappingTable[".*"];
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
static MimeHelper()
|
||||
{
|
||||
MimeHelper._mimeMappingTable = new Hashtable(190, StringComparer.CurrentCultureIgnoreCase);
|
||||
MimeHelper.AddMimeMapping(".323", "text/h323");
|
||||
MimeHelper.AddMimeMapping(".asx", "video/x-ms-asf");
|
||||
MimeHelper.AddMimeMapping(".acx", "application/internet-property-stream");
|
||||
MimeHelper.AddMimeMapping(".ai", "application/postscript");
|
||||
MimeHelper.AddMimeMapping(".aif", "audio/x-aiff");
|
||||
MimeHelper.AddMimeMapping(".aiff", "audio/aiff");
|
||||
MimeHelper.AddMimeMapping(".axs", "application/olescript");
|
||||
MimeHelper.AddMimeMapping(".aifc", "audio/aiff");
|
||||
MimeHelper.AddMimeMapping(".asr", "video/x-ms-asf");
|
||||
MimeHelper.AddMimeMapping(".avi", "video/x-msvideo");
|
||||
MimeHelper.AddMimeMapping(".asf", "video/x-ms-asf");
|
||||
MimeHelper.AddMimeMapping(".au", "audio/basic");
|
||||
MimeHelper.AddMimeMapping(".application", "application/x-ms-application");
|
||||
MimeHelper.AddMimeMapping(".bin", "application/octet-stream");
|
||||
MimeHelper.AddMimeMapping(".bas", "text/plain");
|
||||
MimeHelper.AddMimeMapping(".bcpio", "application/x-bcpio");
|
||||
MimeHelper.AddMimeMapping(".bmp", "image/bmp");
|
||||
MimeHelper.AddMimeMapping(".cdf", "application/x-cdf");
|
||||
MimeHelper.AddMimeMapping(".cat", "application/vndms-pkiseccat");
|
||||
MimeHelper.AddMimeMapping(".crt", "application/x-x509-ca-cert");
|
||||
MimeHelper.AddMimeMapping(".c", "text/plain");
|
||||
MimeHelper.AddMimeMapping(".css", "text/css");
|
||||
MimeHelper.AddMimeMapping(".cer", "application/x-x509-ca-cert");
|
||||
MimeHelper.AddMimeMapping(".crl", "application/pkix-crl");
|
||||
MimeHelper.AddMimeMapping(".cmx", "image/x-cmx");
|
||||
MimeHelper.AddMimeMapping(".csh", "application/x-csh");
|
||||
MimeHelper.AddMimeMapping(".cod", "image/cis-cod");
|
||||
MimeHelper.AddMimeMapping(".cpio", "application/x-cpio");
|
||||
MimeHelper.AddMimeMapping(".clp", "application/x-msclip");
|
||||
MimeHelper.AddMimeMapping(".crd", "application/x-mscardfile");
|
||||
MimeHelper.AddMimeMapping(".deploy", "application/octet-stream");
|
||||
MimeHelper.AddMimeMapping(".dll", "application/x-msdownload");
|
||||
MimeHelper.AddMimeMapping(".dot", "application/msword");
|
||||
MimeHelper.AddMimeMapping(".doc", "application/msword");
|
||||
MimeHelper.AddMimeMapping(".dvi", "application/x-dvi");
|
||||
MimeHelper.AddMimeMapping(".dir", "application/x-director");
|
||||
MimeHelper.AddMimeMapping(".dxr", "application/x-director");
|
||||
MimeHelper.AddMimeMapping(".der", "application/x-x509-ca-cert");
|
||||
MimeHelper.AddMimeMapping(".dib", "image/bmp");
|
||||
MimeHelper.AddMimeMapping(".dcr", "application/x-director");
|
||||
MimeHelper.AddMimeMapping(".disco", "text/xml");
|
||||
MimeHelper.AddMimeMapping(".exe", "application/octet-stream");
|
||||
MimeHelper.AddMimeMapping(".etx", "text/x-setext");
|
||||
MimeHelper.AddMimeMapping(".evy", "application/envoy");
|
||||
MimeHelper.AddMimeMapping(".eml", "message/rfc822");
|
||||
MimeHelper.AddMimeMapping(".eps", "application/postscript");
|
||||
MimeHelper.AddMimeMapping(".flr", "x-world/x-vrml");
|
||||
MimeHelper.AddMimeMapping(".fif", "application/fractals");
|
||||
MimeHelper.AddMimeMapping(".gtar", "application/x-gtar");
|
||||
MimeHelper.AddMimeMapping(".gif", "image/gif");
|
||||
MimeHelper.AddMimeMapping(".gz", "application/x-gzip");
|
||||
MimeHelper.AddMimeMapping(".hta", "application/hta");
|
||||
MimeHelper.AddMimeMapping(".htc", "text/x-component");
|
||||
MimeHelper.AddMimeMapping(".htt", "text/webviewhtml");
|
||||
MimeHelper.AddMimeMapping(".h", "text/plain");
|
||||
MimeHelper.AddMimeMapping(".hdf", "application/x-hdf");
|
||||
MimeHelper.AddMimeMapping(".hlp", "application/winhlp");
|
||||
MimeHelper.AddMimeMapping(".html", "text/html");
|
||||
MimeHelper.AddMimeMapping(".htm", "text/html");
|
||||
MimeHelper.AddMimeMapping(".hqx", "application/mac-binhex40");
|
||||
MimeHelper.AddMimeMapping(".isp", "application/x-internet-signup");
|
||||
MimeHelper.AddMimeMapping(".iii", "application/x-iphone");
|
||||
MimeHelper.AddMimeMapping(".ief", "image/ief");
|
||||
MimeHelper.AddMimeMapping(".ivf", "video/x-ivf");
|
||||
MimeHelper.AddMimeMapping(".ins", "application/x-internet-signup");
|
||||
MimeHelper.AddMimeMapping(".ico", "image/x-icon");
|
||||
MimeHelper.AddMimeMapping(".jpg", "image/jpeg");
|
||||
MimeHelper.AddMimeMapping(".jfif", "image/pjpeg");
|
||||
MimeHelper.AddMimeMapping(".jpe", "image/jpeg");
|
||||
MimeHelper.AddMimeMapping(".jpeg", "image/jpeg");
|
||||
MimeHelper.AddMimeMapping(".js", "application/x-javascript");
|
||||
MimeHelper.AddMimeMapping(".lsx", "video/x-la-asf");
|
||||
MimeHelper.AddMimeMapping(".latex", "application/x-latex");
|
||||
MimeHelper.AddMimeMapping(".lsf", "video/x-la-asf");
|
||||
MimeHelper.AddMimeMapping(".manifest", "application/x-ms-manifest");
|
||||
MimeHelper.AddMimeMapping(".mhtml", "message/rfc822");
|
||||
MimeHelper.AddMimeMapping(".mny", "application/x-msmoney");
|
||||
MimeHelper.AddMimeMapping(".mht", "message/rfc822");
|
||||
MimeHelper.AddMimeMapping(".mid", "audio/mid");
|
||||
MimeHelper.AddMimeMapping(".mpv2", "video/mpeg");
|
||||
MimeHelper.AddMimeMapping(".man", "application/x-troff-man");
|
||||
MimeHelper.AddMimeMapping(".mvb", "application/x-msmediaview");
|
||||
MimeHelper.AddMimeMapping(".mpeg", "video/mpeg");
|
||||
MimeHelper.AddMimeMapping(".m3u", "audio/x-mpegurl");
|
||||
MimeHelper.AddMimeMapping(".mdb", "application/x-msaccess");
|
||||
MimeHelper.AddMimeMapping(".mpp", "application/vnd.ms-project");
|
||||
MimeHelper.AddMimeMapping(".m1v", "video/mpeg");
|
||||
MimeHelper.AddMimeMapping(".mpa", "video/mpeg");
|
||||
MimeHelper.AddMimeMapping(".me", "application/x-troff-me");
|
||||
MimeHelper.AddMimeMapping(".m13", "application/x-msmediaview");
|
||||
MimeHelper.AddMimeMapping(".movie", "video/x-sgi-movie");
|
||||
MimeHelper.AddMimeMapping(".m14", "application/x-msmediaview");
|
||||
MimeHelper.AddMimeMapping(".mpe", "video/mpeg");
|
||||
MimeHelper.AddMimeMapping(".mp2", "video/mpeg");
|
||||
MimeHelper.AddMimeMapping(".mov", "video/quicktime");
|
||||
MimeHelper.AddMimeMapping(".mp3", "audio/mpeg");
|
||||
MimeHelper.AddMimeMapping(".mpg", "video/mpeg");
|
||||
MimeHelper.AddMimeMapping(".ms", "application/x-troff-ms");
|
||||
MimeHelper.AddMimeMapping(".nc", "application/x-netcdf");
|
||||
MimeHelper.AddMimeMapping(".nws", "message/rfc822");
|
||||
MimeHelper.AddMimeMapping(".oda", "application/oda");
|
||||
MimeHelper.AddMimeMapping(".ods", "application/oleobject");
|
||||
MimeHelper.AddMimeMapping(".pmc", "application/x-perfmon");
|
||||
MimeHelper.AddMimeMapping(".p7r", "application/x-pkcs7-certreqresp");
|
||||
MimeHelper.AddMimeMapping(".p7b", "application/x-pkcs7-certificates");
|
||||
MimeHelper.AddMimeMapping(".p7s", "application/pkcs7-signature");
|
||||
MimeHelper.AddMimeMapping(".pmw", "application/x-perfmon");
|
||||
MimeHelper.AddMimeMapping(".ps", "application/postscript");
|
||||
MimeHelper.AddMimeMapping(".p7c", "application/pkcs7-mime");
|
||||
MimeHelper.AddMimeMapping(".pbm", "image/x-portable-bitmap");
|
||||
MimeHelper.AddMimeMapping(".ppm", "image/x-portable-pixmap");
|
||||
MimeHelper.AddMimeMapping(".pub", "application/x-mspublisher");
|
||||
MimeHelper.AddMimeMapping(".pnm", "image/x-portable-anymap");
|
||||
MimeHelper.AddMimeMapping(".png", "image/png");
|
||||
MimeHelper.AddMimeMapping(".pml", "application/x-perfmon");
|
||||
MimeHelper.AddMimeMapping(".p10", "application/pkcs10");
|
||||
MimeHelper.AddMimeMapping(".pfx", "application/x-pkcs12");
|
||||
MimeHelper.AddMimeMapping(".p12", "application/x-pkcs12");
|
||||
MimeHelper.AddMimeMapping(".pdf", "application/pdf");
|
||||
MimeHelper.AddMimeMapping(".pps", "application/vnd.ms-powerpoint");
|
||||
MimeHelper.AddMimeMapping(".p7m", "application/pkcs7-mime");
|
||||
MimeHelper.AddMimeMapping(".pko", "application/vndms-pkipko");
|
||||
MimeHelper.AddMimeMapping(".ppt", "application/vnd.ms-powerpoint");
|
||||
MimeHelper.AddMimeMapping(".pmr", "application/x-perfmon");
|
||||
MimeHelper.AddMimeMapping(".pma", "application/x-perfmon");
|
||||
MimeHelper.AddMimeMapping(".pot", "application/vnd.ms-powerpoint");
|
||||
MimeHelper.AddMimeMapping(".prf", "application/pics-rules");
|
||||
MimeHelper.AddMimeMapping(".pgm", "image/x-portable-graymap");
|
||||
MimeHelper.AddMimeMapping(".qt", "video/quicktime");
|
||||
MimeHelper.AddMimeMapping(".ra", "audio/x-pn-realaudio");
|
||||
MimeHelper.AddMimeMapping(".rgb", "image/x-rgb");
|
||||
MimeHelper.AddMimeMapping(".ram", "audio/x-pn-realaudio");
|
||||
MimeHelper.AddMimeMapping(".rmi", "audio/mid");
|
||||
MimeHelper.AddMimeMapping(".ras", "image/x-cmu-raster");
|
||||
MimeHelper.AddMimeMapping(".roff", "application/x-troff");
|
||||
MimeHelper.AddMimeMapping(".rtf", "application/rtf");
|
||||
MimeHelper.AddMimeMapping(".rtx", "text/richtext");
|
||||
MimeHelper.AddMimeMapping(".sv4crc", "application/x-sv4crc");
|
||||
MimeHelper.AddMimeMapping(".spc", "application/x-pkcs7-certificates");
|
||||
MimeHelper.AddMimeMapping(".setreg", "application/set-registration-initiation");
|
||||
MimeHelper.AddMimeMapping(".snd", "audio/basic");
|
||||
MimeHelper.AddMimeMapping(".stl", "application/vndms-pkistl");
|
||||
MimeHelper.AddMimeMapping(".setpay", "application/set-payment-initiation");
|
||||
MimeHelper.AddMimeMapping(".stm", "text/html");
|
||||
MimeHelper.AddMimeMapping(".shar", "application/x-shar");
|
||||
MimeHelper.AddMimeMapping(".sh", "application/x-sh");
|
||||
MimeHelper.AddMimeMapping(".sit", "application/x-stuffit");
|
||||
MimeHelper.AddMimeMapping(".spl", "application/futuresplash");
|
||||
MimeHelper.AddMimeMapping(".sct", "text/scriptlet");
|
||||
MimeHelper.AddMimeMapping(".scd", "application/x-msschedule");
|
||||
MimeHelper.AddMimeMapping(".sst", "application/vndms-pkicertstore");
|
||||
MimeHelper.AddMimeMapping(".src", "application/x-wais-source");
|
||||
MimeHelper.AddMimeMapping(".sv4cpio", "application/x-sv4cpio");
|
||||
MimeHelper.AddMimeMapping(".tex", "application/x-tex");
|
||||
MimeHelper.AddMimeMapping(".tgz", "application/x-compressed");
|
||||
MimeHelper.AddMimeMapping(".t", "application/x-troff");
|
||||
MimeHelper.AddMimeMapping(".tar", "application/x-tar");
|
||||
MimeHelper.AddMimeMapping(".tr", "application/x-troff");
|
||||
MimeHelper.AddMimeMapping(".tif", "image/tiff");
|
||||
MimeHelper.AddMimeMapping(".txt", "text/plain");
|
||||
MimeHelper.AddMimeMapping(".texinfo", "application/x-texinfo");
|
||||
MimeHelper.AddMimeMapping(".trm", "application/x-msterminal");
|
||||
MimeHelper.AddMimeMapping(".tiff", "image/tiff");
|
||||
MimeHelper.AddMimeMapping(".tcl", "application/x-tcl");
|
||||
MimeHelper.AddMimeMapping(".texi", "application/x-texinfo");
|
||||
MimeHelper.AddMimeMapping(".tsv", "text/tab-separated-values");
|
||||
MimeHelper.AddMimeMapping(".ustar", "application/x-ustar");
|
||||
MimeHelper.AddMimeMapping(".uls", "text/iuls");
|
||||
MimeHelper.AddMimeMapping(".vcf", "text/x-vcard");
|
||||
MimeHelper.AddMimeMapping(".wps", "application/vnd.ms-works");
|
||||
MimeHelper.AddMimeMapping(".wav", "audio/wav");
|
||||
MimeHelper.AddMimeMapping(".wrz", "x-world/x-vrml");
|
||||
MimeHelper.AddMimeMapping(".wri", "application/x-mswrite");
|
||||
MimeHelper.AddMimeMapping(".wks", "application/vnd.ms-works");
|
||||
MimeHelper.AddMimeMapping(".wmf", "application/x-msmetafile");
|
||||
MimeHelper.AddMimeMapping(".wcm", "application/vnd.ms-works");
|
||||
MimeHelper.AddMimeMapping(".wrl", "x-world/x-vrml");
|
||||
MimeHelper.AddMimeMapping(".wdb", "application/vnd.ms-works");
|
||||
MimeHelper.AddMimeMapping(".wsdl", "text/xml");
|
||||
MimeHelper.AddMimeMapping(".xap", "application/x-silverlight-app");
|
||||
MimeHelper.AddMimeMapping(".xml", "text/xml");
|
||||
MimeHelper.AddMimeMapping(".xlm", "application/vnd.ms-excel");
|
||||
MimeHelper.AddMimeMapping(".xaf", "x-world/x-vrml");
|
||||
MimeHelper.AddMimeMapping(".xla", "application/vnd.ms-excel");
|
||||
MimeHelper.AddMimeMapping(".xls", "application/vnd.ms-excel");
|
||||
MimeHelper.AddMimeMapping(".xlsx", "application/vnd.ms-excel");
|
||||
MimeHelper.AddMimeMapping(".xof", "x-world/x-vrml");
|
||||
MimeHelper.AddMimeMapping(".xlt", "application/vnd.ms-excel");
|
||||
MimeHelper.AddMimeMapping(".xlc", "application/vnd.ms-excel");
|
||||
MimeHelper.AddMimeMapping(".xsl", "text/xml");
|
||||
MimeHelper.AddMimeMapping(".xbm", "image/x-xbitmap");
|
||||
MimeHelper.AddMimeMapping(".xlw", "application/vnd.ms-excel");
|
||||
MimeHelper.AddMimeMapping(".xpm", "image/x-xpixmap");
|
||||
MimeHelper.AddMimeMapping(".xwd", "image/x-xwindowdump");
|
||||
MimeHelper.AddMimeMapping(".xsd", "text/xml");
|
||||
MimeHelper.AddMimeMapping(".z", "application/x-compress");
|
||||
MimeHelper.AddMimeMapping(".zip", "application/x-zip-compressed");
|
||||
MimeHelper.AddMimeMapping(".*", "application/octet-stream");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
390
Yi.Framework.Net6/Yi.Framework.Common/Helper/RSAHelper.cs
Normal file
@@ -0,0 +1,390 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace Yi.Framework.Common.Helper
|
||||
{
|
||||
/// <summary>
|
||||
/// RSA加解密 使用OpenSSL的公钥加密/私钥解密
|
||||
/// 公私钥请使用openssl生成
|
||||
/// </summary>
|
||||
public class RSAHelper
|
||||
{
|
||||
public readonly RSA _privateKeyRsaProvider;
|
||||
public readonly RSA _publicKeyRsaProvider;
|
||||
private readonly HashAlgorithmName _hashAlgorithmName;
|
||||
private readonly Encoding _encoding;
|
||||
|
||||
/// <summary>
|
||||
/// 实例化RSAHelper
|
||||
/// </summary>
|
||||
/// <param name="rsaType">加密算法类型 RSA SHA1;RSA2 SHA256 密钥长度至少为2048</param>
|
||||
/// <param name="encoding">编码类型</param>
|
||||
/// <param name="privateKey">私钥</param>
|
||||
/// <param name="publicKey">公钥</param>
|
||||
public RSAHelper(RSAType rsaType, Encoding encoding, string privateKey, string publicKey = null)
|
||||
{
|
||||
_encoding = encoding;
|
||||
if (!string.IsNullOrEmpty(privateKey))
|
||||
{
|
||||
_privateKeyRsaProvider = CreateRsaProviderFromPrivateKey(privateKey);
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(publicKey))
|
||||
{
|
||||
_publicKeyRsaProvider = CreateRsaProviderFromPublicKey(publicKey);
|
||||
}
|
||||
|
||||
_hashAlgorithmName = rsaType == RSAType.RSA ? HashAlgorithmName.SHA1 : HashAlgorithmName.SHA256;
|
||||
}
|
||||
|
||||
#region 使用私钥签名
|
||||
|
||||
/// <summary>
|
||||
/// 使用私钥签名
|
||||
/// </summary>
|
||||
/// <param name="data">原始数据</param>
|
||||
/// <returns></returns>
|
||||
public string Sign(string data)
|
||||
{
|
||||
byte[] dataBytes = _encoding.GetBytes(data);
|
||||
|
||||
var signatureBytes = _privateKeyRsaProvider.SignData(dataBytes, _hashAlgorithmName, RSASignaturePadding.Pkcs1);
|
||||
|
||||
return Convert.ToBase64String(signatureBytes);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 使用公钥验签
|
||||
|
||||
/// <summary>
|
||||
/// 使用公钥验签
|
||||
/// </summary>
|
||||
/// <param name="data">原始数据</param>
|
||||
/// <param name="sign">签名</param>
|
||||
/// <returns></returns>
|
||||
public bool Verify(string data, string sign)
|
||||
{
|
||||
byte[] dataBytes = _encoding.GetBytes(data);
|
||||
byte[] signBytes = Convert.FromBase64String(sign);
|
||||
|
||||
var verify = _publicKeyRsaProvider.VerifyData(dataBytes, signBytes, _hashAlgorithmName, RSASignaturePadding.Pkcs1);
|
||||
|
||||
return verify;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 解密
|
||||
/// <summary>
|
||||
/// 私钥解密(原)
|
||||
/// </summary>
|
||||
/// <param name="cipherText">解密字符串(base64)</param>
|
||||
/// <returns></returns>
|
||||
|
||||
//public string Decrypt(string cipherText)
|
||||
//{
|
||||
// if (_privateKeyRsaProvider == null)
|
||||
// {
|
||||
// throw new Exception("_privateKeyRsaProvider is null");
|
||||
// }
|
||||
// return _encoding.GetString(_privateKeyRsaProvider.Decrypt(Convert.FromBase64String(cipherText), RSAEncryptionPadding.Pkcs1));
|
||||
//}
|
||||
/// <summary>
|
||||
/// 私钥解密(支持大量数据)
|
||||
/// </summary>
|
||||
/// <param name="cipherText"></param>
|
||||
/// <returns></returns>
|
||||
public string Decrypt(string cipherText)
|
||||
{
|
||||
if (_privateKeyRsaProvider == null)
|
||||
{
|
||||
throw new Exception("_privateKeyRsaProvider is null");
|
||||
}
|
||||
var bufferSize = (_privateKeyRsaProvider.KeySize / 8);
|
||||
byte[] buffer = new byte[bufferSize];//待解密块
|
||||
using (MemoryStream msInput = new MemoryStream(Convert.FromBase64String(cipherText)))
|
||||
{
|
||||
using (MemoryStream msOutput = new MemoryStream())
|
||||
{
|
||||
int readLen; while ((readLen = msInput.Read(buffer, 0, bufferSize)) > 0)
|
||||
{
|
||||
byte[] dataToEnc = new byte[readLen];
|
||||
Array.Copy(buffer, 0, dataToEnc, 0, readLen); byte[] encData = _privateKeyRsaProvider.Decrypt(dataToEnc, RSAEncryptionPadding.Pkcs1);
|
||||
msOutput.Write(encData, 0, encData.Length);
|
||||
}
|
||||
byte[] result = msOutput.ToArray();
|
||||
return _encoding.GetString(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 加密
|
||||
|
||||
/// <summary>
|
||||
/// 公钥加密(原)
|
||||
/// </summary>
|
||||
/// <param name="text"></param>
|
||||
/// <returns></returns>
|
||||
//public string Encrypt(string text)
|
||||
//{
|
||||
// if (_publicKeyRsaProvider == null)
|
||||
// {
|
||||
// throw new Exception("_publicKeyRsaProvider is null");
|
||||
// }
|
||||
// return Convert.ToBase64String(_publicKeyRsaProvider.Encrypt(Encoding.UTF8.GetBytes(text), RSAEncryptionPadding.Pkcs1));
|
||||
//}
|
||||
/// <summary>
|
||||
/// 公钥加密(支持大量数据)
|
||||
/// </summary>
|
||||
/// <param name="text"></param>
|
||||
/// <returns></returns>
|
||||
public string Encrypt(string text)
|
||||
{
|
||||
if (_publicKeyRsaProvider == null)
|
||||
{
|
||||
throw new Exception("_publicKeyRsaProvider is null");
|
||||
}
|
||||
var bufferSize = (_publicKeyRsaProvider.KeySize / 8 - 11);
|
||||
byte[] buffer = new byte[bufferSize];//待加密块
|
||||
|
||||
using (MemoryStream msInput = new MemoryStream(_encoding.GetBytes(text)))
|
||||
{
|
||||
using (MemoryStream msOutput = new MemoryStream())
|
||||
{
|
||||
int readLen; while ((readLen = msInput.Read(buffer, 0, bufferSize)) > 0)
|
||||
{
|
||||
byte[] dataToEnc = new byte[readLen];
|
||||
Array.Copy(buffer, 0, dataToEnc, 0, readLen); byte[] encData = _publicKeyRsaProvider.Encrypt(dataToEnc, RSAEncryptionPadding.Pkcs1);
|
||||
msOutput.Write(encData, 0, encData.Length);
|
||||
}
|
||||
byte[] result = msOutput.ToArray();
|
||||
return Convert.ToBase64String(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 使用私钥创建RSA实例
|
||||
/// <summary>
|
||||
/// 使用私钥创建RSA实例
|
||||
/// </summary>
|
||||
/// <param name="privateKey"></param>
|
||||
/// <returns></returns>
|
||||
private RSA CreateRsaProviderFromPrivateKey(string privateKey)
|
||||
{
|
||||
var privateKeyBits = Convert.FromBase64String(privateKey);
|
||||
|
||||
var rsa = RSA.Create();
|
||||
var rsaParameters = new RSAParameters();
|
||||
|
||||
using (BinaryReader binr = new BinaryReader(new MemoryStream(privateKeyBits)))
|
||||
{
|
||||
byte bt = 0;
|
||||
ushort twobytes = 0;
|
||||
twobytes = binr.ReadUInt16();
|
||||
if (twobytes == 0x8130)
|
||||
binr.ReadByte();
|
||||
else if (twobytes == 0x8230)
|
||||
binr.ReadInt16();
|
||||
else
|
||||
throw new Exception("Unexpected value read binr.ReadUInt16()");
|
||||
|
||||
twobytes = binr.ReadUInt16();
|
||||
if (twobytes != 0x0102)
|
||||
throw new Exception("Unexpected version");
|
||||
|
||||
bt = binr.ReadByte();
|
||||
if (bt != 0x00)
|
||||
throw new Exception("Unexpected value read binr.ReadByte()");
|
||||
|
||||
rsaParameters.Modulus = binr.ReadBytes(GetIntegerSize(binr));
|
||||
rsaParameters.Exponent = binr.ReadBytes(GetIntegerSize(binr));
|
||||
rsaParameters.D = binr.ReadBytes(GetIntegerSize(binr));
|
||||
rsaParameters.P = binr.ReadBytes(GetIntegerSize(binr));
|
||||
rsaParameters.Q = binr.ReadBytes(GetIntegerSize(binr));
|
||||
rsaParameters.DP = binr.ReadBytes(GetIntegerSize(binr));
|
||||
rsaParameters.DQ = binr.ReadBytes(GetIntegerSize(binr));
|
||||
rsaParameters.InverseQ = binr.ReadBytes(GetIntegerSize(binr));
|
||||
}
|
||||
|
||||
rsa.ImportParameters(rsaParameters);
|
||||
return rsa;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 使用公钥创建RSA实例
|
||||
/// <summary>
|
||||
/// 使用公钥创建RSA实例
|
||||
/// </summary>
|
||||
/// <param name="publicKeyString"></param>
|
||||
/// <returns></returns>
|
||||
public RSA CreateRsaProviderFromPublicKey(string publicKeyString)
|
||||
{
|
||||
// encoded OID sequence for PKCS #1 rsaEncryption szOID_RSA_RSA = "1.2.840.113549.1.1.1"
|
||||
byte[] seqOid = { 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 };
|
||||
byte[] seq = new byte[15];
|
||||
|
||||
var x509Key = Convert.FromBase64String(publicKeyString);
|
||||
|
||||
// --------- Set up stream to read the asn.1 encoded SubjectPublicKeyInfo blob ------
|
||||
using (MemoryStream mem = new MemoryStream(x509Key))
|
||||
{
|
||||
using (BinaryReader binr = new BinaryReader(mem)) //wrap Memory Stream with BinaryReader for easy reading
|
||||
{
|
||||
byte bt = 0;
|
||||
ushort twobytes = 0;
|
||||
|
||||
twobytes = binr.ReadUInt16();
|
||||
if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
|
||||
binr.ReadByte(); //advance 1 byte
|
||||
else if (twobytes == 0x8230)
|
||||
binr.ReadInt16(); //advance 2 bytes
|
||||
else
|
||||
return null;
|
||||
|
||||
seq = binr.ReadBytes(15); //read the Sequence OID
|
||||
if (!CompareBytearrays(seq, seqOid)) //make sure Sequence for OID is correct
|
||||
return null;
|
||||
|
||||
twobytes = binr.ReadUInt16();
|
||||
if (twobytes == 0x8103) //data read as little endian order (actual data order for Bit String is 03 81)
|
||||
binr.ReadByte(); //advance 1 byte
|
||||
else if (twobytes == 0x8203)
|
||||
binr.ReadInt16(); //advance 2 bytes
|
||||
else
|
||||
return null;
|
||||
|
||||
bt = binr.ReadByte();
|
||||
if (bt != 0x00) //expect null byte next
|
||||
return null;
|
||||
|
||||
twobytes = binr.ReadUInt16();
|
||||
if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
|
||||
binr.ReadByte(); //advance 1 byte
|
||||
else if (twobytes == 0x8230)
|
||||
binr.ReadInt16(); //advance 2 bytes
|
||||
else
|
||||
return null;
|
||||
|
||||
twobytes = binr.ReadUInt16();
|
||||
byte lowbyte = 0x00;
|
||||
byte highbyte = 0x00;
|
||||
|
||||
if (twobytes == 0x8102) //data read as little endian order (actual data order for Integer is 02 81)
|
||||
lowbyte = binr.ReadByte(); // read next bytes which is bytes in modulus
|
||||
else if (twobytes == 0x8202)
|
||||
{
|
||||
highbyte = binr.ReadByte(); //advance 2 bytes
|
||||
lowbyte = binr.ReadByte();
|
||||
}
|
||||
else
|
||||
return null;
|
||||
byte[] modint = { lowbyte, highbyte, 0x00, 0x00 }; //reverse byte order since asn.1 key uses big endian order
|
||||
int modsize = BitConverter.ToInt32(modint, 0);
|
||||
|
||||
int firstbyte = binr.PeekChar();
|
||||
if (firstbyte == 0x00)
|
||||
{ //if first byte (highest order) of modulus is zero, don't include it
|
||||
binr.ReadByte(); //skip this null byte
|
||||
modsize -= 1; //reduce modulus buffer size by 1
|
||||
}
|
||||
|
||||
byte[] modulus = binr.ReadBytes(modsize); //read the modulus bytes
|
||||
|
||||
if (binr.ReadByte() != 0x02) //expect an Integer for the exponent data
|
||||
return null;
|
||||
int expbytes = (int)binr.ReadByte(); // should only need one byte for actual exponent data (for all useful values)
|
||||
byte[] exponent = binr.ReadBytes(expbytes);
|
||||
|
||||
// ------- create RSACryptoServiceProvider instance and initialize with public key -----
|
||||
var rsa = RSA.Create();
|
||||
RSAParameters rsaKeyInfo = new RSAParameters
|
||||
{
|
||||
Modulus = modulus,
|
||||
Exponent = exponent
|
||||
};
|
||||
rsa.ImportParameters(rsaKeyInfo);
|
||||
|
||||
return rsa;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 导入密钥算法
|
||||
|
||||
private int GetIntegerSize(BinaryReader binr)
|
||||
{
|
||||
byte bt = 0;
|
||||
int count = 0;
|
||||
bt = binr.ReadByte();
|
||||
if (bt != 0x02)
|
||||
return 0;
|
||||
bt = binr.ReadByte();
|
||||
|
||||
if (bt == 0x81)
|
||||
count = binr.ReadByte();
|
||||
else
|
||||
if (bt == 0x82)
|
||||
{
|
||||
var highbyte = binr.ReadByte();
|
||||
var lowbyte = binr.ReadByte();
|
||||
byte[] modint = { lowbyte, highbyte, 0x00, 0x00 };
|
||||
count = BitConverter.ToInt32(modint, 0);
|
||||
}
|
||||
else
|
||||
{
|
||||
count = bt;
|
||||
}
|
||||
|
||||
while (binr.ReadByte() == 0x00)
|
||||
{
|
||||
count -= 1;
|
||||
}
|
||||
binr.BaseStream.Seek(-1, SeekOrigin.Current);
|
||||
return count;
|
||||
}
|
||||
|
||||
private bool CompareBytearrays(byte[] a, byte[] b)
|
||||
{
|
||||
if (a.Length != b.Length)
|
||||
return false;
|
||||
int i = 0;
|
||||
foreach (byte c in a)
|
||||
{
|
||||
if (c != b[i])
|
||||
return false;
|
||||
i++;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// RSA算法类型
|
||||
/// </summary>
|
||||
public enum RSAType
|
||||
{
|
||||
/// <summary>
|
||||
/// SHA1
|
||||
/// </summary>
|
||||
RSA = 0,
|
||||
/// <summary>
|
||||
/// RSA2 密钥长度至少为2048
|
||||
/// SHA256
|
||||
/// </summary>
|
||||
RSA2
|
||||
}
|
||||
}
|
||||
99
Yi.Framework.Net6/Yi.Framework.Common/Helper/RandomHelper.cs
Normal file
@@ -0,0 +1,99 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Yi.Framework.Common.Helper
|
||||
{
|
||||
public class RandomHelper
|
||||
{
|
||||
public static string replaceBianLiang(string content)
|
||||
{
|
||||
content = content.Replace("{当前时间}", DateTime.Now.TimeOfDay.ToString());
|
||||
string[] bianliang = new string[] { "{随机字母}", "{随机数字}", "{随机汉字}" };
|
||||
Regex r;
|
||||
int count;
|
||||
string readstr = "";
|
||||
foreach (string str in bianliang)
|
||||
{
|
||||
count = (content.Length - content.Replace(str, "").Length) / str.Length;
|
||||
if (str == "{随机汉字}") readstr = RandChina(count);
|
||||
if (str == "{随机数字}") readstr = GenerateCheckCodeNum(count);
|
||||
if (str == "{随机字母}") readstr = GenerateRandomLetter(count);
|
||||
if (count > readstr.Length) count = readstr.Length;
|
||||
r = new Regex(str.Replace("{", "\\{").Replace("}", "\\}"));
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
content = r.Replace(content, readstr.Substring(i, 1), 1);
|
||||
}
|
||||
}
|
||||
return content;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 随机生成字母
|
||||
/// </summary>
|
||||
/// <param name="Length"></param>
|
||||
/// <returns></returns>
|
||||
public static string GenerateRandomLetter(int Length)
|
||||
{
|
||||
char[] Pattern = new char[] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
|
||||
string result = "";
|
||||
int n = Pattern.Length;
|
||||
Random random = new Random(~unchecked((int)DateTime.Now.Ticks));
|
||||
for (int i = 0; i < Length; i++)
|
||||
{
|
||||
int rnd = random.Next(0, n);
|
||||
result += Pattern[rnd];
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 随机生成数字
|
||||
/// </summary>
|
||||
/// <param name="codeCount"></param>
|
||||
/// <returns></returns>
|
||||
public static string GenerateCheckCodeNum(int codeCount)
|
||||
{
|
||||
int rep = 0;
|
||||
string str = string.Empty;
|
||||
long num2 = DateTime.Now.Ticks + rep;
|
||||
rep++;
|
||||
Random random = new Random(((int)(((ulong)num2) & 0xffffffffL)) | ((int)(num2 >> rep)));
|
||||
for (int i = 0; i < codeCount; i++)
|
||||
{
|
||||
int num = random.Next();
|
||||
str = str + ((char)(0x30 + ((ushort)(num % 10)))).ToString();
|
||||
}
|
||||
return str;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 此函数为生成指定数目的汉字
|
||||
/// </summary>
|
||||
/// <param name="charLen">汉字数目</param>
|
||||
/// <returns>所有汉字</returns>
|
||||
public static string RandChina(int charLen)
|
||||
{
|
||||
int area, code;//汉字由区位和码位组成(都为0-94,其中区位16-55为一级汉字区,56-87为二级汉字区,1-9为特殊字符区)
|
||||
StringBuilder strtem = new StringBuilder();
|
||||
Random rand = new Random();
|
||||
for (int i = 0; i < charLen; i++)
|
||||
{
|
||||
area = rand.Next(16, 88);
|
||||
if (area == 55)//第55区只有89个字符
|
||||
{
|
||||
code = rand.Next(1, 90);
|
||||
}
|
||||
else
|
||||
{
|
||||
code = rand.Next(1, 94);
|
||||
}
|
||||
strtem.Append(Encoding.GetEncoding("GB2312").GetString(new byte[] { Convert.ToByte(area + 160), Convert.ToByte(code + 160) }));
|
||||
}
|
||||
return strtem.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
using Newtonsoft.Json;
|
||||
using System.Text;
|
||||
|
||||
namespace Yi.Framework.Common.Helper
|
||||
{
|
||||
public class SerializeHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// 序列化
|
||||
/// </summary>
|
||||
/// <param name="item"></param>
|
||||
/// <returns></returns>
|
||||
public static byte[] Serialize(object item)
|
||||
{
|
||||
var jsonString = JsonConvert.SerializeObject(item);
|
||||
|
||||
return Encoding.UTF8.GetBytes(jsonString);
|
||||
}
|
||||
/// <summary>
|
||||
/// 反序列化
|
||||
/// </summary>
|
||||
/// <typeparam name="TEntity"></typeparam>
|
||||
/// <param name="value"></param>
|
||||
/// <returns></returns>
|
||||
public static TEntity Deserialize<TEntity>(byte[] value)
|
||||
{
|
||||
if (value == null)
|
||||
{
|
||||
return default(TEntity);
|
||||
}
|
||||
var jsonString = Encoding.UTF8.GetString(value);
|
||||
return JsonConvert.DeserializeObject<TEntity>(jsonString);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Yi.Framework.Common.Helper
|
||||
{
|
||||
public static class SnowflakeHelper
|
||||
{
|
||||
public static long Next()
|
||||
{
|
||||
SnowflakeTool snowflakeTool = new SnowflakeTool(1);
|
||||
return snowflakeTool.NextId();
|
||||
}
|
||||
|
||||
private class SnowflakeTool
|
||||
{
|
||||
//机器ID
|
||||
private static long nodeId;
|
||||
private static long twepoch = 687888001020L; //唯一时间,这是一个避免重复的随机量,自行设定不要大于当前时间戳
|
||||
private static long sequence = 0L;
|
||||
private static int workerIdBits = 4; //机器码字节数。4个字节用来保存机器码(定义为Long类型会出现,最大偏移64位,所以左移64位没有意义)
|
||||
public static long maxWorkerId = -1L ^ -1L << workerIdBits; //最大机器ID
|
||||
private static int sequenceBits = 10; //计数器字节数,10个字节用来保存计数码
|
||||
private static int workerIdShift = sequenceBits; //机器码数据左移位数,就是后面计数器占用的位数
|
||||
private static int timestampLeftShift = sequenceBits + workerIdBits; //时间戳左移动位数就是机器码和计数器总字节数
|
||||
public static long sequenceMask = -1L ^ -1L << sequenceBits; //一微秒内可以产生计数,如果达到该值则等到下一微妙在进行生成
|
||||
private long lastTimestamp = -1L;
|
||||
|
||||
/// <summary>
|
||||
/// 机器码
|
||||
/// </summary>
|
||||
/// <param name="workerId"></param>
|
||||
public SnowflakeTool(long workerId)
|
||||
{
|
||||
if (workerId > maxWorkerId || workerId < 0)
|
||||
throw new Exception(string.Format("节点id 不能大于 {0} 或者 小于 0 ", workerId));
|
||||
SnowflakeTool.nodeId = workerId;
|
||||
|
||||
}
|
||||
|
||||
public long NextId()
|
||||
{
|
||||
lock (this)
|
||||
{
|
||||
long timestamp = TimeGen();
|
||||
if (this.lastTimestamp == timestamp)
|
||||
{ //同一微妙中生成ID
|
||||
SnowflakeTool.sequence = (SnowflakeTool.sequence + 1) & SnowflakeTool.sequenceMask; //用&运算计算该微秒内产生的计数是否已经到达上限
|
||||
if (SnowflakeTool.sequence == 0)
|
||||
{
|
||||
//一微妙内产生的ID计数已达上限,等待下一微妙
|
||||
timestamp = TillNextMillis(this.lastTimestamp);
|
||||
}
|
||||
}
|
||||
else
|
||||
{ //不同微秒生成ID
|
||||
SnowflakeTool.sequence = 0; //计数清0
|
||||
}
|
||||
if (timestamp < lastTimestamp)
|
||||
{ //如果当前时间戳比上一次生成ID时时间戳还小,抛出异常,因为不能保证现在生成的ID之前没有生成过
|
||||
throw new Exception(string.Format("Clock moved backwards. Refusing to generate id for {0} milliseconds",
|
||||
this.lastTimestamp - timestamp));
|
||||
}
|
||||
this.lastTimestamp = timestamp; //把当前时间戳保存为最后生成ID的时间戳
|
||||
long nextId = (timestamp - twepoch << timestampLeftShift) | SnowflakeTool.nodeId << SnowflakeTool.workerIdShift | SnowflakeTool.sequence;
|
||||
return nextId;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取下一微秒时间戳
|
||||
/// </summary>
|
||||
/// <param name="lastTimestamp"></param>
|
||||
/// <returns></returns>
|
||||
private long TillNextMillis(long lastTimestamp)
|
||||
{
|
||||
long timestamp = TimeGen();
|
||||
while (timestamp <= lastTimestamp)
|
||||
{
|
||||
timestamp = TimeGen();
|
||||
}
|
||||
return timestamp;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 生成当前时间戳
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
private long TimeGen()
|
||||
{
|
||||
return (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
111
Yi.Framework.Net6/Yi.Framework.Common/Helper/StringHelper.cs
Normal file
@@ -0,0 +1,111 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Yi.Framework.Common.Helper
|
||||
{
|
||||
public class StringHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// 根据分隔符返回前n条数据
|
||||
/// </summary>
|
||||
/// <param name="content">数据内容</param>
|
||||
/// <param name="separator">分隔符</param>
|
||||
/// <param name="top">前n条</param>
|
||||
/// <param name="isDesc">是否倒序(默认false)</param>
|
||||
/// <returns></returns>
|
||||
public static List<string> GetTopDataBySeparator(string content, string separator, int top, bool isDesc = false)
|
||||
{
|
||||
if (string.IsNullOrEmpty(content))
|
||||
{
|
||||
return new List<string>() { };
|
||||
}
|
||||
|
||||
if (string.IsNullOrEmpty(separator))
|
||||
{
|
||||
throw new ArgumentException("message", nameof(separator));
|
||||
}
|
||||
|
||||
var dataArray = content.Split(separator).Where(d => !string.IsNullOrEmpty(d)).ToArray();
|
||||
if (isDesc)
|
||||
{
|
||||
Array.Reverse(dataArray);
|
||||
}
|
||||
|
||||
if (top > 0)
|
||||
{
|
||||
dataArray = dataArray.Take(top).ToArray();
|
||||
}
|
||||
|
||||
return dataArray.ToList();
|
||||
}
|
||||
/// <summary>
|
||||
/// 根据字段拼接get参数
|
||||
/// </summary>
|
||||
/// <param name="dic"></param>
|
||||
/// <returns></returns>
|
||||
public static string GetPars(Dictionary<string, object> dic)
|
||||
{
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
string urlPars = null;
|
||||
bool isEnter = false;
|
||||
foreach (var item in dic)
|
||||
{
|
||||
sb.Append($"{(isEnter ? "&" : "")}{item.Key}={item.Value}");
|
||||
isEnter = true;
|
||||
}
|
||||
urlPars = sb.ToString();
|
||||
return urlPars;
|
||||
}
|
||||
/// <summary>
|
||||
/// 根据字段拼接get参数
|
||||
/// </summary>
|
||||
/// <param name="dic"></param>
|
||||
/// <returns></returns>
|
||||
public static string GetPars(Dictionary<string, string> dic)
|
||||
{
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
string urlPars = null;
|
||||
bool isEnter = false;
|
||||
foreach (var item in dic)
|
||||
{
|
||||
sb.Append($"{(isEnter ? "&" : "")}{item.Key}={item.Value}");
|
||||
isEnter = true;
|
||||
}
|
||||
urlPars = sb.ToString();
|
||||
return urlPars;
|
||||
}
|
||||
/// <summary>
|
||||
/// 获取一个GUID
|
||||
/// </summary>
|
||||
/// <param name="format">格式-默认为N</param>
|
||||
/// <returns></returns>
|
||||
public static string GetGUID(string format="N") {
|
||||
return Guid.NewGuid().ToString(format);
|
||||
}
|
||||
/// <summary>
|
||||
/// 根据GUID获取19位的唯一数字序列
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static long GetGuidToLongID()
|
||||
{
|
||||
byte[] buffer = Guid.NewGuid().ToByteArray();
|
||||
return BitConverter.ToInt64(buffer, 0);
|
||||
}
|
||||
/// <summary>
|
||||
/// 获取字符串最后X行
|
||||
/// </summary>
|
||||
/// <param name="resourceStr"></param>
|
||||
/// <param name="length"></param>
|
||||
/// <returns></returns>
|
||||
public static string GetCusLine(string resourceStr, int length) {
|
||||
string[] arrStr = resourceStr.Split("\r\n");
|
||||
return string.Join("", (from q in arrStr select q).Skip(arrStr.Length - length + 1).Take(length).ToArray());
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
using System;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Yi.Framework.Common.Helper
|
||||
{
|
||||
public static class UnicodeHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// 字符串转Unicode码
|
||||
/// </summary>
|
||||
/// <returns>The to unicode.</returns>
|
||||
/// <param name="value">Value.</param>
|
||||
public static string StringToUnicode(string value)
|
||||
{
|
||||
byte[] bytes = Encoding.Unicode.GetBytes(value);
|
||||
StringBuilder stringBuilder = new StringBuilder();
|
||||
for (int i = 0; i < bytes.Length; i += 2)
|
||||
{
|
||||
// 取两个字符,每个字符都是右对齐。
|
||||
stringBuilder.AppendFormat("u{0}{1}", bytes[i + 1].ToString("x").PadLeft(2, '0'), bytes[i].ToString("x").PadLeft(2, '0'));
|
||||
}
|
||||
return stringBuilder.ToString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Unicode转字符串
|
||||
/// </summary>
|
||||
/// <returns>The to string.</returns>
|
||||
/// <param name="unicode">Unicode.</param>
|
||||
public static string UnicodeToString(string unicode)
|
||||
{
|
||||
unicode = unicode.Replace("%", "\\");
|
||||
|
||||
return new Regex(@"\\u([0-9A-F]{4})", RegexOptions.IgnoreCase | RegexOptions.Compiled).Replace(
|
||||
unicode, x => string.Empty + Convert.ToChar(Convert.ToUInt16(x.Result("$1"), 16)));
|
||||
|
||||
//string resultStr = "";
|
||||
//string[] strList = unicode.Split('u');
|
||||
//for (int i = 1; i < strList.Length; i++)
|
||||
//{
|
||||
// resultStr += (char)int.Parse(strList[i], System.Globalization.NumberStyles.HexNumber);
|
||||
//}
|
||||
//return resultStr;
|
||||
}
|
||||
}
|
||||
}
|
||||
23
Yi.Framework.Net6/Yi.Framework.Common/Helper/UrlHelper.cs
Normal file
@@ -0,0 +1,23 @@
|
||||
namespace Yi.Framework.Common.Helper
|
||||
{
|
||||
public class UrlHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// UrlEncode编码
|
||||
/// </summary>
|
||||
/// <param name="url">url</param>
|
||||
/// <returns></returns>
|
||||
public static string UrlEncode(string url) {
|
||||
return System.Web.HttpUtility.UrlEncode(url, System.Text.Encoding.UTF8);
|
||||
}
|
||||
/// <summary>
|
||||
/// UrlEncode解码
|
||||
/// </summary>
|
||||
/// <param name="data">数据</param>
|
||||
/// <returns></returns>
|
||||
public static string UrlDecode(string data)
|
||||
{
|
||||
return System.Web.HttpUtility.UrlDecode(data, System.Text.Encoding.UTF8);
|
||||
}
|
||||
}
|
||||
}
|
||||
51
Yi.Framework.Net6/Yi.Framework.Common/Helper/XmlHelper.cs
Normal file
@@ -0,0 +1,51 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Xml.Serialization;
|
||||
|
||||
namespace Yi.Framework.Common.Helper
|
||||
{
|
||||
public class XmlHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// 转换对象为JSON格式数据
|
||||
/// </summary>
|
||||
/// <typeparam name="T">类</typeparam>
|
||||
/// <param name="obj">对象</param>
|
||||
/// <returns>字符格式的JSON数据</returns>
|
||||
public static string GetXML<T>(object obj)
|
||||
{
|
||||
try
|
||||
{
|
||||
XmlSerializer xs = new XmlSerializer(typeof(T));
|
||||
|
||||
using (TextWriter tw = new StringWriter())
|
||||
{
|
||||
xs.Serialize(tw, obj);
|
||||
return tw.ToString();
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Xml格式字符转换为T类型的对象
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="xml"></param>
|
||||
/// <returns></returns>
|
||||
public static T ParseFormByXml<T>(string xml,string rootName="root")
|
||||
{
|
||||
XmlSerializer serializer = new XmlSerializer(typeof(T), new XmlRootAttribute(rootName));
|
||||
StringReader reader = new StringReader(xml);
|
||||
|
||||
T res = (T)serializer.Deserialize(reader);
|
||||
reader.Close();
|
||||
reader.Dispose();
|
||||
return res;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace Yi.Framework.Common.IOCOptions
|
||||
{
|
||||
/// <summary>
|
||||
/// 使用Consul时需要配置
|
||||
/// </summary>
|
||||
public class ConsulClientOption
|
||||
{
|
||||
public string IP { get; set; }
|
||||
public int Port { get; set; }
|
||||
public string Datacenter { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Yi.Framework.Common.IOCOptions
|
||||
{
|
||||
public class ConsulRegisterOption
|
||||
{
|
||||
/// <summary>
|
||||
/// 服务自身IP
|
||||
/// </summary>
|
||||
public string IP { get; set; }
|
||||
/// <summary>
|
||||
/// 服务自身Port
|
||||
/// </summary>
|
||||
public int Port { get; set; }
|
||||
/// <summary>
|
||||
/// 组名称
|
||||
/// </summary>
|
||||
public string GroupName { get; set; }
|
||||
/// <summary>
|
||||
/// 心跳检查地址
|
||||
/// </summary>
|
||||
public string HealthCheckUrl { get; set; }
|
||||
/// <summary>
|
||||
/// 心跳频率
|
||||
/// </summary>
|
||||
public int Interval { get; set; }
|
||||
/// <summary>
|
||||
/// 心跳超时
|
||||
/// </summary>
|
||||
public int Timeout { get; set; }
|
||||
/// <summary>
|
||||
/// 移除延迟时间
|
||||
/// </summary>
|
||||
public int DeregisterCriticalServiceAfter { get; set; }
|
||||
/// <summary>
|
||||
/// 标签,额外信息,用于权重
|
||||
/// </summary>
|
||||
public string Tag { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Yi.Framework.Common.IOCOptions
|
||||
{
|
||||
public class ElasticSearchOptions
|
||||
{
|
||||
public string Url { get; set; }
|
||||
public string IndexName { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Yi.Framework.Common.IOCOptions
|
||||
{
|
||||
public class KafkaOptions
|
||||
{
|
||||
public string BrokerList { get; set; }
|
||||
public string TopicName { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Yi.Framework.Common.IOCOptions
|
||||
{
|
||||
public class DbConnOptions
|
||||
{
|
||||
public string WriteUrl { get; set; }
|
||||
public List<string> ReadUrl { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Yi.Framework.Common.IOCOptions
|
||||
{
|
||||
public class RabbitMQOptions
|
||||
{
|
||||
///// <summary>
|
||||
///// exchange---queue
|
||||
///// </summary>
|
||||
//private static Dictionary<string, string> RabbitMQ_Mapping = new Dictionary<string, string>();
|
||||
//private static readonly object RabbitMQOptions_Lock = new object();
|
||||
//public void Init(string exchangeName, string queueName)
|
||||
//{
|
||||
// lock (RabbitMQOptions_Lock)
|
||||
// {
|
||||
// RabbitMQ_Mapping[exchangeName] = queueName;
|
||||
// }
|
||||
//}
|
||||
|
||||
public string HostName { get; set; }
|
||||
public string UserName { get; set; }
|
||||
public string Password { get; set; }
|
||||
|
||||
public int Port { get; set; }
|
||||
|
||||
}
|
||||
|
||||
public class RabbitMQConsumerModel
|
||||
{
|
||||
/// <summary>
|
||||
/// 生产者指定,交换机
|
||||
/// </summary>
|
||||
public string ExchangeName { get; set; }
|
||||
/// <summary>
|
||||
/// 自己起的名字
|
||||
/// </summary>
|
||||
public string QueueName { get; set; }
|
||||
}
|
||||
|
||||
public class RabbitMQExchangeQueueName
|
||||
{
|
||||
public static readonly string SKUCQRS_Exchange = "Zhaoxi.MSACormmerce.SKUCQRS.Exchange";
|
||||
public static readonly string SKUCQRS_Queue_StaticPage = "Zhaoxi.MSACormmerce.SKUCQRS.Queue.StaticPage";
|
||||
public static readonly string SKUCQRS_Queue_ESIndex = "Zhaoxi.MSACormmerce.SKUCQRS.Queue.ESIndex";
|
||||
|
||||
|
||||
public static readonly string SKUWarmup_Exchange = "Zhaoxi.MSACormmerce.Warmup.Exchange";
|
||||
public static readonly string SKUWarmup_Queue_StaticPage = "Zhaoxi.MSACormmerce.Warmup.Queue.StaticPage";
|
||||
public static readonly string SKUWarmup_Queue_ESIndex = "Zhaoxi.MSACormmerce.Warmup.Queue.ESIndex";
|
||||
|
||||
/// <summary>
|
||||
/// 订单创建后的交换机
|
||||
/// </summary>
|
||||
public static readonly string OrderCreate_Exchange = "Zhaoxi.MSACormmerce.OrderCreate.Exchange";
|
||||
public static readonly string OrderCreate_Queue_CleanCart = "Zhaoxi.MSACormmerce.OrderCreate.Queue.CleanCart";
|
||||
|
||||
/// <summary>
|
||||
/// 订单创建后的交换机,支付状态的
|
||||
/// </summary>
|
||||
public static readonly string OrderPay_Exchange = "Zhaoxi.MSACormmerce.OrderPay.Exchange";
|
||||
public static readonly string OrderPay_Queue_RefreshPay = "Zhaoxi.MSACormmerce.OrderPay.Queue.RefreshPay";
|
||||
|
||||
/// <summary>
|
||||
/// 创建订单后的延时队列配置
|
||||
/// </summary>
|
||||
public static readonly string OrderCreate_Delay_Exchange = "Zhaoxi.MSACormmerce.OrderCreate.DelayExchange";
|
||||
public static readonly string OrderCreate_Delay_Queue_CancelOrder = "Zhaoxi.MSACormmerce.OrderCreate.DelayQueue.CancelOrder";
|
||||
|
||||
/// <summary>
|
||||
/// 秒杀异步的
|
||||
/// </summary>
|
||||
public static readonly string Seckill_Exchange = "Zhaoxi.MSACormmerce.Seckill.Exchange";
|
||||
public static readonly string Seckill_Order_Queue = "Zhaoxi.MSACormmerce.Seckill.Order.Queue";
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// CAP队列名称
|
||||
/// </summary>
|
||||
public const string Order_Stock_Decrease = "RabbitMQ.MySQL.Order-Stock.Decrease";
|
||||
public const string Order_Stock_Resume = "RabbitMQ.MySQL.Order-Stock.Resume";
|
||||
public const string Stock_Logistics = "RabbitMQ.MySQL.Stock-Logistics";
|
||||
|
||||
public const string Pay_Order_UpdateStatus = "RabbitMQ.MySQL.Pay_Order.UpdateStatus";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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 RedisConnOptions
|
||||
{
|
||||
public string Host { get; set; }
|
||||
public int DB { get; set; } = 0;
|
||||
public int Prot { get; set; }
|
||||
public string Password { get; set; }
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -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 SMSOptions
|
||||
{
|
||||
|
||||
public string ID { get; set; }
|
||||
public string Secret { get; set; }
|
||||
public string Sign { get; set; }
|
||||
public string Template { get; set; }
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Yi.Framework.Common.IOCOptions
|
||||
{
|
||||
public class SqliteOptions
|
||||
{
|
||||
public string WriteUrl { get; set; }
|
||||
public List<string> ReadUrl { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Yi.Framework.Common.Models
|
||||
{
|
||||
public class AxiosUrlsModel
|
||||
{
|
||||
public string get { get; set; }
|
||||
public string update { get; set; }
|
||||
public string del { get; set; }
|
||||
public string add { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace Yi.Framework.Common.Enum
|
||||
{
|
||||
public enum AgrFlagEnum
|
||||
{
|
||||
wait = 0,
|
||||
Agree = 1
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace Yi.Framework.Common.Enum
|
||||
{
|
||||
public enum DelFlagEnum
|
||||
{
|
||||
Normal=0,
|
||||
Deleted=1
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Yi.Framework.Common.Enum
|
||||
{
|
||||
public enum ShowFlagEnum
|
||||
{
|
||||
NoShow=0,
|
||||
Show=1
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Yi.Framework.Common.Enum
|
||||
{
|
||||
public enum TopFlagEnum
|
||||
{
|
||||
Children=0,
|
||||
Top=1
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace Yi.Framework.Common.Enum
|
||||
{
|
||||
public enum WriteAndReadEnum
|
||||
{
|
||||
Write, //主库操作
|
||||
Read //从库操作
|
||||
}
|
||||
}
|
||||
13
Yi.Framework.Net6/Yi.Framework.Common/Models/JobModel.cs
Normal file
@@ -0,0 +1,13 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Yi.Framework.Common.Models
|
||||
{
|
||||
public class JobModel
|
||||
{
|
||||
public static int visitNum { get; set; } = 0;
|
||||
}
|
||||
}
|
||||
18
Yi.Framework.Net6/Yi.Framework.Common/Models/LogModel.cs
Normal file
@@ -0,0 +1,18 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Yi.Framework.Common.Models
|
||||
{
|
||||
/// <summary>
|
||||
/// 写入分布式日志需要的字段
|
||||
/// </summary>
|
||||
public class LogModel
|
||||
{
|
||||
public string OriginalClassName { get; set; }
|
||||
public string OriginalMethodName { get; set; }
|
||||
public string Remark { get; set; }
|
||||
}
|
||||
}
|
||||
13
Yi.Framework.Net6/Yi.Framework.Common/Models/PageModel.cs
Normal file
@@ -0,0 +1,13 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Yi.Framework.Common.Models
|
||||
{
|
||||
public class PageModel
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
77
Yi.Framework.Net6/Yi.Framework.Common/Models/Result.cs
Normal file
@@ -0,0 +1,77 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Web;
|
||||
|
||||
namespace Yi.Framework.Common.Models
|
||||
{
|
||||
/// <summary>
|
||||
/// 结果数据
|
||||
/// </summary>
|
||||
public class Result
|
||||
{
|
||||
public bool status { get; set; }
|
||||
public int code { get; set; }
|
||||
public string msg { get; set; }
|
||||
public object 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 };
|
||||
}
|
||||
public static Result Success(string msg = "succeed")
|
||||
{
|
||||
return new Result() { status = true, code = 200, msg = msg };
|
||||
}
|
||||
public static Result UnAuthorize(string msg = "unAuthorize")
|
||||
{
|
||||
return new Result() { status = false, code = 401, msg = msg };
|
||||
}
|
||||
|
||||
public Result SetData(object obj)
|
||||
{
|
||||
this.data = obj;
|
||||
return this;
|
||||
}
|
||||
public Result SetCode(int Code)
|
||||
{
|
||||
this.code = Code;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
public class Result<T>
|
||||
{
|
||||
public bool status { get; set; }
|
||||
public int code { get; set; }
|
||||
public string msg { get; set; }
|
||||
public T data { get; set; }
|
||||
|
||||
public static Result<T> Instance(bool status, string msg)
|
||||
{
|
||||
return new Result<T>() { status = status, code = 500, msg = msg };
|
||||
}
|
||||
public static Result<T> Error(string msg = "fail")
|
||||
{
|
||||
return new Result<T> { status = false, code = 500, msg = msg };
|
||||
}
|
||||
public static Result<T> Success(string msg = "succeed")
|
||||
{
|
||||
return new Result<T> { status = true, code = 200, msg = msg };
|
||||
}
|
||||
|
||||
public static Result<T> UnAuthorize(string msg = "unAuthorize")
|
||||
{
|
||||
return new Result<T>{ status = false, code = 401, msg = msg };
|
||||
}
|
||||
|
||||
public Result<T> SetData(T TValue)
|
||||
{
|
||||
this.data = TValue;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
19
Yi.Framework.Net6/Yi.Framework.Common/Models/SwaggerModel.cs
Normal file
@@ -0,0 +1,19 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Yi.Framework.Common.Models
|
||||
{
|
||||
public class SwaggerModel
|
||||
{
|
||||
public SwaggerModel(string url, string name)
|
||||
{
|
||||
this.url = url;
|
||||
this.name = name;
|
||||
}
|
||||
public string url { get; set; }
|
||||
public string name { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Yi.Framework.Common.QueueModel
|
||||
{
|
||||
/// <summary>
|
||||
/// 下单成功后的实体
|
||||
/// </summary>
|
||||
public class OrderCreateQueueModel
|
||||
{
|
||||
/// <summary>
|
||||
/// 用户Id
|
||||
/// </summary>
|
||||
public long UserId { get; set; }
|
||||
/// <summary>
|
||||
/// 订单Id
|
||||
/// </summary>
|
||||
public long OrderId { get; set; }
|
||||
/// <summary>
|
||||
/// sku ID 集合
|
||||
/// </summary>
|
||||
public List<long> SkuIdList { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 尝试次数
|
||||
/// </summary>
|
||||
public int TryTime { get; set; }
|
||||
|
||||
public OrderTypeEnum OrderType { get; set; }
|
||||
|
||||
public enum OrderTypeEnum
|
||||
{
|
||||
Normal,
|
||||
Seckill
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Yi.Framework.Common.QueueModel
|
||||
{
|
||||
public class SKUWarmupQueueModel
|
||||
{
|
||||
public bool Warmup { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Yi.Framework.Common.QueueModel
|
||||
{
|
||||
public class SMSQueueModel
|
||||
{
|
||||
public string code { get; set; }
|
||||
public string phone { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Yi.Framework.Common.QueueModel
|
||||
{
|
||||
/// <summary>
|
||||
/// 以SPU为单位
|
||||
/// </summary>
|
||||
public class SPUCQRSQueueModel
|
||||
{
|
||||
public long SpuId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// enum SPUCQRSQueueModelType
|
||||
/// </summary>
|
||||
public int CQRSType { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 操作类型
|
||||
/// </summary>
|
||||
public enum SPUCQRSQueueModelType
|
||||
{
|
||||
Insert = 0,
|
||||
Update = 1,
|
||||
Delete = 2,
|
||||
Search = 3
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net6.0</TargetFramework>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="EPPlus" Version="5.8.4" />
|
||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
1074
Yi.Framework.Net6/Yi.Framework.Core/CacheClientDB.cs
Normal file
@@ -0,0 +1,72 @@
|
||||
using Consul;
|
||||
using Microsoft.Extensions.Options;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Yi.Framework.Common.IOCOptions;
|
||||
|
||||
namespace Yi.Framework.Core.ConsulExtend
|
||||
{
|
||||
public abstract class AbstractConsulDispatcher
|
||||
{
|
||||
protected ConsulClientOption _ConsulClientOption = null;
|
||||
protected KeyValuePair<string, AgentService>[] _CurrentAgentServiceDictionary = null;
|
||||
|
||||
public AbstractConsulDispatcher(IOptionsMonitor<ConsulClientOption> consulClientOption)
|
||||
{
|
||||
this._ConsulClientOption = consulClientOption.CurrentValue;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 负载均衡获取地址
|
||||
/// </summary>
|
||||
/// <param name="mappingUrl">Consul映射后的地址</param>
|
||||
/// <returns></returns>
|
||||
public string GetAddress(string mappingUrl)
|
||||
{
|
||||
Uri uri = new Uri(mappingUrl);
|
||||
string serviceName = uri.Host;
|
||||
string addressPort = this.ChooseAddress(serviceName);
|
||||
return $"{uri.Scheme}://{addressPort}{uri.PathAndQuery}";
|
||||
}
|
||||
|
||||
protected virtual string ChooseAddress(string serviceName)
|
||||
{
|
||||
ConsulClient client = new ConsulClient(c =>
|
||||
{
|
||||
c.Address = new Uri($"http://{this._ConsulClientOption.IP}:{this._ConsulClientOption.Port}/");
|
||||
c.Datacenter = this._ConsulClientOption.Datacenter;
|
||||
});
|
||||
AgentService agentService = null;
|
||||
//var response = client.Agent.Services().Result.Response;
|
||||
////foreach (var item in response)
|
||||
////{
|
||||
//// Console.WriteLine("***************************************");
|
||||
//// Console.WriteLine(item.Key);
|
||||
//// var service = item.Value;
|
||||
//// Console.WriteLine($"{service.Address}--{service.Port}--{service.Service}");
|
||||
//// Console.WriteLine("***************************************");
|
||||
////}
|
||||
|
||||
//this._CurrentAgentServiceDictionary = response.Where(s => s.Value.Service.Equals(serviceName, StringComparison.OrdinalIgnoreCase)).ToArray();
|
||||
|
||||
//升级consul实例获取
|
||||
var entrys = client.Health.Service(serviceName).Result.Response;
|
||||
List<KeyValuePair<string, AgentService>> serviceList = new List<KeyValuePair<string, AgentService>>();
|
||||
for (int i = 0; i < entrys.Length; i++)
|
||||
{
|
||||
serviceList.Add(new KeyValuePair<string, AgentService>(i.ToString(), entrys[i].Service));
|
||||
}
|
||||
this._CurrentAgentServiceDictionary = serviceList.ToArray();
|
||||
|
||||
int index = this.GetIndex();
|
||||
agentService = this._CurrentAgentServiceDictionary[index].Value;
|
||||
|
||||
return $"{agentService.Address}:{agentService.Port}";
|
||||
}
|
||||
|
||||
protected abstract int GetIndex();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Consul;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Yi.Framework.Common.IOCOptions;
|
||||
|
||||
namespace Yi.Framework.Core.ConsulExtend
|
||||
{
|
||||
/// <summary>
|
||||
/// 平均
|
||||
/// </summary>
|
||||
public class AverageDispatcher : AbstractConsulDispatcher
|
||||
{
|
||||
#region Identity
|
||||
private static int _iTotalCount = 0;
|
||||
private static int iTotalCount
|
||||
{
|
||||
get
|
||||
{
|
||||
return _iTotalCount;
|
||||
}
|
||||
set
|
||||
{
|
||||
_iTotalCount = value >= Int32.MaxValue ? 0 : value;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public AverageDispatcher(IOptionsMonitor<ConsulClientOption> consulClientOption) : base(consulClientOption)
|
||||
{
|
||||
}
|
||||
#endregion
|
||||
|
||||
/// <summary>
|
||||
/// 平均
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
protected override int GetIndex()
|
||||
{
|
||||
return new Random(iTotalCount++).Next(0, base._CurrentAgentServiceDictionary.Length);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Consul;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Yi.Framework.Common.IOCOptions;
|
||||
|
||||
namespace Yi.Framework.Core.ConsulExtend
|
||||
{
|
||||
/// <summary>
|
||||
/// 轮询
|
||||
/// </summary>
|
||||
public class PollingDispatcher : AbstractConsulDispatcher
|
||||
{
|
||||
#region Identity
|
||||
private static int _iTotalCount = 0;
|
||||
private static int iTotalCount
|
||||
{
|
||||
get
|
||||
{
|
||||
return _iTotalCount;
|
||||
}
|
||||
set
|
||||
{
|
||||
_iTotalCount = value >= Int32.MaxValue ? 0 : value;
|
||||
}
|
||||
}
|
||||
|
||||
public PollingDispatcher(IOptionsMonitor<ConsulClientOption> consulClientOption) : base(consulClientOption)
|
||||
{
|
||||
}
|
||||
#endregion
|
||||
|
||||
/// <summary>
|
||||
/// 轮询
|
||||
/// </summary>
|
||||
/// <param name="serviceCount"></param>
|
||||
/// <returns></returns>
|
||||
protected override int GetIndex()
|
||||
{
|
||||
return iTotalCount++ % base._CurrentAgentServiceDictionary.Length;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Consul;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Yi.Framework.Common.IOCOptions;
|
||||
|
||||
namespace Yi.Framework.Core.ConsulExtend
|
||||
{
|
||||
/// <summary>
|
||||
/// 权重
|
||||
/// </summary>
|
||||
public class WeightDispatcher : AbstractConsulDispatcher
|
||||
{
|
||||
#region Identity
|
||||
private static int _iTotalCount = 0;
|
||||
private static int iTotalCount
|
||||
{
|
||||
get
|
||||
{
|
||||
return _iTotalCount;
|
||||
}
|
||||
set
|
||||
{
|
||||
_iTotalCount = value >= Int32.MaxValue ? 0 : value;
|
||||
}
|
||||
}
|
||||
public WeightDispatcher(IOptionsMonitor<ConsulClientOption> consulClientOption) : base(consulClientOption)
|
||||
{
|
||||
|
||||
}
|
||||
#endregion
|
||||
|
||||
protected override string ChooseAddress(string serviceName)
|
||||
{
|
||||
ConsulClient client = new ConsulClient(c =>
|
||||
{
|
||||
c.Address = new Uri($"http://{base._ConsulClientOption.IP}:{base._ConsulClientOption.Port}/");
|
||||
c.Datacenter = base._ConsulClientOption.Datacenter;
|
||||
});
|
||||
AgentService agentService = null;
|
||||
var response = client.Agent.Services().Result.Response;
|
||||
|
||||
this._CurrentAgentServiceDictionary = response.Where(s => s.Value.Service.Equals(serviceName, StringComparison.OrdinalIgnoreCase)).ToArray();
|
||||
|
||||
|
||||
var serviceDictionaryNew = new List<AgentService>();
|
||||
foreach (var service in base._CurrentAgentServiceDictionary)
|
||||
{
|
||||
serviceDictionaryNew.AddRange(Enumerable.Repeat(service.Value, int.TryParse(service.Value.Tags?[0], out int iWeight) ? 1 : iWeight));
|
||||
}
|
||||
int index = new Random(DateTime.Now.Millisecond).Next(0, int.MaxValue) % serviceDictionaryNew.Count;
|
||||
agentService = serviceDictionaryNew[index];
|
||||
|
||||
return $"{agentService.Address}:{agentService.Port}";
|
||||
}
|
||||
/// <summary>
|
||||
/// 不需要了
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
protected override int GetIndex()
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
}
|
||||
53
Yi.Framework.Net6/Yi.Framework.Core/ElasticSearchInvoker.cs
Normal file
@@ -0,0 +1,53 @@
|
||||
using Microsoft.Extensions.Options;
|
||||
using Nest;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Yi.Framework.Common.IOCOptions;
|
||||
|
||||
namespace Yi.Framework.Core
|
||||
{
|
||||
public class ElasticSearchInvoker
|
||||
{
|
||||
private readonly ElasticSearchOptions _elasticSearchOptions;
|
||||
|
||||
public ElasticSearchInvoker(IOptionsMonitor<ElasticSearchOptions> optionsMonitor)
|
||||
{
|
||||
_elasticSearchOptions = optionsMonitor.CurrentValue;
|
||||
var settings = new ConnectionSettings(new Uri(_elasticSearchOptions.Url)).DefaultIndex(this._elasticSearchOptions.IndexName);
|
||||
Client = new ElasticClient(settings);
|
||||
}
|
||||
private ElasticClient Client;
|
||||
public ElasticClient GetElasticClient()
|
||||
{
|
||||
return Client;
|
||||
}
|
||||
public void Send<T>(List<T> model) where T : class
|
||||
{
|
||||
Client.IndexMany(model);
|
||||
}
|
||||
|
||||
public void InsertOrUpdata<T>(T model) where T : class
|
||||
{
|
||||
Client.IndexDocument(model);
|
||||
}
|
||||
|
||||
public bool Delete<T>(string id) where T : class
|
||||
{
|
||||
|
||||
var response = Client.Delete<T>(id);
|
||||
return response.IsValid;
|
||||
}
|
||||
public bool DropIndex(string indexName)
|
||||
{
|
||||
return Client.Indices.Delete(Indices.Parse(indexName)).IsValid;
|
||||
}
|
||||
public void CreateIndex(string indexName)
|
||||
{
|
||||
var settings = new ConnectionSettings(new Uri(_elasticSearchOptions.Url)).DefaultIndex(indexName);
|
||||
this.Client = new ElasticClient(settings);
|
||||
}
|
||||
}
|
||||
}
|
||||
63
Yi.Framework.Net6/Yi.Framework.Core/MakeJwt.cs
Normal file
@@ -0,0 +1,63 @@
|
||||
using Microsoft.IdentityModel.JsonWebTokens;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Linq;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Yi.Framework.Common.Const;
|
||||
using Yi.Framework.Model.Models;
|
||||
using JwtRegisteredClaimNames = Microsoft.IdentityModel.JsonWebTokens.JwtRegisteredClaimNames;
|
||||
|
||||
namespace Yi.Framework.Core
|
||||
{
|
||||
|
||||
public class jwtUser
|
||||
{
|
||||
public user user { get; set; }
|
||||
public List<menu> menuIds { get; set; }
|
||||
|
||||
}
|
||||
|
||||
public class MakeJwt
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// user需关联所有roles,还有一个menuIds
|
||||
/// </summary>
|
||||
/// <param name="_user"></param>
|
||||
/// <returns></returns>
|
||||
public static string app(jwtUser _user)
|
||||
{
|
||||
//通过查询权限,把所有权限加入进令牌中
|
||||
List<Claim> claims = new List<Claim>();
|
||||
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()));
|
||||
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));
|
||||
}
|
||||
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(JwtConst.SecurityKey));
|
||||
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
|
||||
|
||||
var token = new JwtSecurityToken(
|
||||
issuer: JwtConst.Domain,
|
||||
audience: JwtConst.Domain,
|
||||
claims: claims,
|
||||
expires: DateTime.Now.AddMinutes(30),
|
||||
signingCredentials: creds);
|
||||
var tokenData = new JwtSecurityTokenHandler().WriteToken(token);
|
||||
|
||||
return tokenData;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Quartz;
|
||||
using Quartz.Spi;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Yi.Framework.Core.Quartz
|
||||
{
|
||||
public class MyQuartzFactory : IJobFactory
|
||||
{
|
||||
private readonly IServiceProvider _serviceProvider;
|
||||
|
||||
public MyQuartzFactory(IServiceProvider serviceProvider)
|
||||
{
|
||||
_serviceProvider = serviceProvider;
|
||||
}
|
||||
|
||||
public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler)
|
||||
{
|
||||
return _serviceProvider.GetRequiredService(bundle.JobDetail.JobType) as IJob;
|
||||
}
|
||||
|
||||
public void ReturnJob(IJob job)
|
||||
{
|
||||
var disposable = job as IDisposable;
|
||||
disposable?.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
150
Yi.Framework.Net6/Yi.Framework.Core/Quartz/QuartzInvoker.cs
Normal file
@@ -0,0 +1,150 @@
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Quartz;
|
||||
using Quartz.Impl.Matchers;
|
||||
using Quartz.Spi;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Yi.Framework.Common.Helper;
|
||||
using Yi.Framework.Job;
|
||||
|
||||
namespace Yi.Framework.Core
|
||||
{
|
||||
public class QuartzInvoker
|
||||
{
|
||||
private readonly ISchedulerFactory _schedulerFactory;
|
||||
private IScheduler _scheduler;
|
||||
private ILogger<QuartzInvoker> _logger;
|
||||
private IJobFactory _jobFactory;
|
||||
public QuartzInvoker(ISchedulerFactory schedulerFactory, ILogger<QuartzInvoker> logger, IJobFactory jobFactory)
|
||||
{
|
||||
_schedulerFactory = schedulerFactory;
|
||||
_logger = logger;
|
||||
_jobFactory = jobFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 开始任务
|
||||
/// </summary>
|
||||
/// <param name="cron"></param>
|
||||
/// <param name="jobKey"></param>
|
||||
/// <param name="jobClass"></param>
|
||||
/// <param name="second"></param>
|
||||
/// <param name="data"></param>
|
||||
/// <returns></returns>
|
||||
public async Task start(string cron, JobKey jobKey, string jobClass, long second = 0, IDictionary<string, object> data = null)
|
||||
{
|
||||
if (data == null)
|
||||
{
|
||||
data = new Dictionary<string, object>();
|
||||
}
|
||||
|
||||
var myClass = AssemblyHelper.GetClass("Yi.Framework.Job", jobClass).FirstOrDefault();
|
||||
|
||||
_scheduler = await _schedulerFactory.GetScheduler();
|
||||
_scheduler.JobFactory = _jobFactory;
|
||||
//开启调度器
|
||||
await _scheduler.Start();
|
||||
//创建一个触发器
|
||||
var trigger = TriggerBuilder.Create()
|
||||
.StartAt(DateTimeOffset.Now.AddSeconds(second))
|
||||
.WithCronSchedule(cron)
|
||||
.Build();
|
||||
//创建任务
|
||||
var jobDetail = JobBuilder.Create(myClass)
|
||||
.UsingJobData(new JobDataMap(data))
|
||||
.WithIdentity(jobKey.Name, jobKey.Group)
|
||||
.Build();
|
||||
//将触发器和任务器绑定到调度器中
|
||||
await _scheduler.ScheduleJob(jobDetail, trigger);
|
||||
|
||||
_logger.LogWarning($"开始任务:{jobKey.Name},组别:{jobKey.Group}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 暂停任务
|
||||
/// </summary>
|
||||
/// <param name="jobKey"></param>
|
||||
/// <returns></returns>
|
||||
public async Task Stop(JobKey jobKey)
|
||||
{
|
||||
var _scheduler = await _schedulerFactory.GetScheduler();
|
||||
//LogUtil.Debug($"暂停任务{jobKey.Group},{jobKey.Name}");
|
||||
await _scheduler.PauseJob(jobKey);
|
||||
_logger.LogWarning($"暂停任务:{jobKey.Name},组别:{jobKey.Group}");
|
||||
}
|
||||
|
||||
|
||||
public async Task Delete(JobKey jobKey)
|
||||
{
|
||||
var _scheduler = await _schedulerFactory.GetScheduler();
|
||||
//LogUtil.Debug($"暂停任务{jobKey.Group},{jobKey.Name}");
|
||||
await _scheduler.DeleteJob(jobKey);
|
||||
_logger.LogWarning($"删除任务:{jobKey.Name},组别:{jobKey.Group}");
|
||||
}
|
||||
|
||||
public async Task Resume(JobKey jobKey)
|
||||
{
|
||||
var _scheduler = await _schedulerFactory.GetScheduler();
|
||||
//LogUtil.Debug($"恢复任务{jobKey.Group},{jobKey.Name}");
|
||||
await _scheduler.ResumeJob(jobKey);
|
||||
_logger.LogWarning($"恢复任务:{jobKey.Name},组别:{jobKey.Group}");
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 得到可运行的job列表
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public List<string> getJobClassList()
|
||||
{
|
||||
var myClassList = AssemblyHelper.GetClass("Yi.Framework.Job");
|
||||
List<string> data = new List<string>();
|
||||
myClassList.ForEach(k => data.Add(k.Name));
|
||||
return data;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 得到现在正在运行的任务列表
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public async Task<List<JobKey>> getRunJobList()
|
||||
{
|
||||
_scheduler = await _schedulerFactory.GetScheduler();
|
||||
var groups = await _scheduler.GetJobGroupNames();
|
||||
var data = new List<JobKey>();
|
||||
foreach (var groupName in groups)
|
||||
{
|
||||
foreach (var jobKey in await _scheduler.GetJobKeys(GroupMatcher<JobKey>.GroupEquals(groupName)))
|
||||
{
|
||||
string jobName = jobKey.Name;
|
||||
string jobGroup = jobKey.Group;
|
||||
data.Add(jobKey);
|
||||
var triggers = await _scheduler.GetTriggersOfJob(jobKey);
|
||||
foreach (ITrigger trigger in triggers)
|
||||
{
|
||||
///下一次的执行时间
|
||||
var utcTime =trigger.GetNextFireTimeUtc();
|
||||
string str = utcTime.ToString();
|
||||
//TimeZone.CurrentTimeZone.ToLocalTime(Convert.ToDateTime(str));
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
public class JobKeyModel
|
||||
{
|
||||
public JobKey jobKey { get; set; }
|
||||
public DateTime? nextTime { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
257
Yi.Framework.Net6/Yi.Framework.Core/RabbitMQInvoker.cs
Normal file
@@ -0,0 +1,257 @@
|
||||
using Microsoft.Extensions.Options;
|
||||
using RabbitMQ.Client;
|
||||
using RabbitMQ.Client.Events;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Yi.Framework.Common.IOCOptions;
|
||||
|
||||
namespace Yi.Framework.Core
|
||||
{
|
||||
/// <summary>
|
||||
/// 一个Exchange----多个Queue-----弄个缓存映射关系,初始化+支持全新绑定
|
||||
/// 全局单例使用
|
||||
///
|
||||
/// 关系应该是直接配置到RabbitMQ了---程序只是向某个位置写入即可
|
||||
///
|
||||
///
|
||||
/// 全量更新--耗时---阻塞实时更新---换不同的exchange?
|
||||
/// </summary>
|
||||
public class RabbitMQInvoker
|
||||
{
|
||||
#region Identity
|
||||
private readonly RabbitMQOptions _rabbitMQOptions;
|
||||
private readonly string _HostName = null;
|
||||
private readonly string _UserName = null;
|
||||
private readonly string _Password = null;
|
||||
private readonly int _Port = 0;
|
||||
public RabbitMQInvoker(IOptionsMonitor<RabbitMQOptions> optionsMonitor) : this(optionsMonitor.CurrentValue.HostName, optionsMonitor.CurrentValue.UserName, optionsMonitor.CurrentValue.Password,optionsMonitor.CurrentValue.Port)
|
||||
{
|
||||
this._rabbitMQOptions = optionsMonitor.CurrentValue;
|
||||
}
|
||||
|
||||
public RabbitMQInvoker(string hostName, string userName = "cc", string password = "cc",int port= 5672)
|
||||
{
|
||||
this._HostName = hostName;
|
||||
this._UserName = userName;
|
||||
this._Password = password;
|
||||
this._Port = port;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Init
|
||||
private static object RabbitMQInvoker_BindQueueLock = new object();
|
||||
private static Dictionary<string, bool> RabbitMQInvoker_ExchangeQueue = new Dictionary<string, bool>();
|
||||
private void InitBindQueue(RabbitMQConsumerModel rabbitMQConsumerModel)
|
||||
{
|
||||
if (!RabbitMQInvoker_ExchangeQueue.ContainsKey($"InitBindQueue_{rabbitMQConsumerModel.ExchangeName}_{rabbitMQConsumerModel.QueueName}"))
|
||||
{
|
||||
lock (RabbitMQInvoker_BindQueueLock)
|
||||
{
|
||||
if (!RabbitMQInvoker_ExchangeQueue.ContainsKey($"InitBindQueue_{rabbitMQConsumerModel.ExchangeName}_{rabbitMQConsumerModel.QueueName}"))
|
||||
{
|
||||
this.InitConnection();
|
||||
using (IModel channel = _CurrentConnection.CreateModel())
|
||||
{
|
||||
channel.ExchangeDeclare(exchange: rabbitMQConsumerModel.ExchangeName, type: ExchangeType.Fanout, durable: true, autoDelete: false, arguments: null);
|
||||
channel.QueueDeclare(queue: rabbitMQConsumerModel.QueueName, durable: true, exclusive: false, autoDelete: false, arguments: null);
|
||||
channel.QueueBind(queue: rabbitMQConsumerModel.QueueName, exchange: rabbitMQConsumerModel.ExchangeName, routingKey: string.Empty, arguments: null);
|
||||
}
|
||||
RabbitMQInvoker_ExchangeQueue[$"InitBindQueue_{rabbitMQConsumerModel.ExchangeName}_{rabbitMQConsumerModel.QueueName}"] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 必须先声明exchange--检查+初始化
|
||||
/// </summary>
|
||||
/// <param name="rabbitMQConsumerModel"></param>
|
||||
private void InitExchange(string exchangeName)
|
||||
{
|
||||
if (!RabbitMQInvoker_ExchangeQueue.ContainsKey($"InitExchange_{exchangeName}"))//没用api确认
|
||||
{
|
||||
lock (RabbitMQInvoker_BindQueueLock)
|
||||
{
|
||||
if (!RabbitMQInvoker_ExchangeQueue.ContainsKey($"InitExchange_{exchangeName}"))
|
||||
{
|
||||
this.InitConnection();
|
||||
using (IModel channel = _CurrentConnection.CreateModel())
|
||||
{
|
||||
channel.ExchangeDeclare(exchange: exchangeName, type: ExchangeType.Fanout, durable: true, autoDelete: false, arguments: null);
|
||||
}
|
||||
RabbitMQInvoker_ExchangeQueue[$"InitExchange_{exchangeName}"] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
//public void UnBindQueue(string exchangeName, string queueName)
|
||||
//{
|
||||
//}
|
||||
|
||||
private static object RabbitMQInvoker_InitLock = new object();
|
||||
private static IConnection _CurrentConnection = null;//链接做成单例重用--channel是新的
|
||||
private void InitConnection()
|
||||
{
|
||||
//https://blog.csdn.net/weixin_30646315/article/details/99101279
|
||||
if (_CurrentConnection == null || !_CurrentConnection.IsOpen)
|
||||
{
|
||||
lock (RabbitMQInvoker_InitLock)
|
||||
{
|
||||
if (_CurrentConnection == null || !_CurrentConnection.IsOpen)
|
||||
{
|
||||
var factory = new ConnectionFactory()
|
||||
{
|
||||
HostName = this._HostName,
|
||||
Password = this._Password,
|
||||
UserName = this._UserName,
|
||||
Port=this._Port
|
||||
|
||||
};
|
||||
_CurrentConnection = factory.CreateConnection();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
/// <summary>
|
||||
/// 只管exchange---
|
||||
/// 4种路由类型?
|
||||
///
|
||||
/// Send前完成交换机初始化
|
||||
/// </summary>
|
||||
/// <param name="exchangeName"></param>
|
||||
/// <param name="message">建议Json格式</param>
|
||||
public void Send(RabbitMQConsumerModel rabbitMQConsumerModel, string message)
|
||||
{
|
||||
this.InitExchange(rabbitMQConsumerModel.ExchangeName);
|
||||
this.InitBindQueue(rabbitMQConsumerModel);
|
||||
if (_CurrentConnection == null || !_CurrentConnection.IsOpen)
|
||||
{
|
||||
this.InitConnection();
|
||||
}
|
||||
using (var channel = _CurrentConnection.CreateModel())//开辟新的信道通信
|
||||
{
|
||||
try
|
||||
{
|
||||
channel.TxSelect();//开启Tx事务---RabbitMQ协议级的事务-----强事务
|
||||
|
||||
var body = Encoding.UTF8.GetBytes(message);
|
||||
channel.BasicPublish(exchange: rabbitMQConsumerModel.ExchangeName,
|
||||
routingKey: string.Empty,
|
||||
basicProperties: null,
|
||||
body: body);
|
||||
channel.TxCommit();//提交
|
||||
Console.WriteLine($" [x] Sent {body.Length}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine(ex.Message);
|
||||
Console.WriteLine($"【{message}】发送到Broker失败!{ex.Message}");
|
||||
channel.TxRollback(); //事务回滚--前面的所有操作就全部作废了。。。。
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 固定无消费队列名字---转移到目标队列---定好时间
|
||||
/// </summary>
|
||||
/// <param name="targetExchangeName"></param>
|
||||
/// <param name="message"></param>
|
||||
/// <param name="delaySecond"></param>
|
||||
public void SendDelay(string targetExchangeName, string message, int delaySecond)
|
||||
{
|
||||
this.InitExchange(targetExchangeName);
|
||||
|
||||
if (_CurrentConnection == null || !_CurrentConnection.IsOpen)
|
||||
{
|
||||
this.InitConnection();
|
||||
}
|
||||
using (var channel = _CurrentConnection.CreateModel())//开辟新的信道通信
|
||||
{
|
||||
try
|
||||
{
|
||||
string delayExchangeName = "ZhaoxiMSA_DelayExchange";
|
||||
|
||||
//普通交换器
|
||||
channel.ExchangeDeclare(delayExchangeName, "fanout", true, false, null);
|
||||
//参数设置
|
||||
Dictionary<string, object> args = new Dictionary<string, object>();
|
||||
args.Add("x-message-ttl", delaySecond * 1000);//TTL 毫秒
|
||||
args.Add("x-dead-letter-exchange", targetExchangeName);//DLX
|
||||
args.Add("x-dead-letter-routing-key", "routingkey");//routingKey
|
||||
channel.QueueDeclare("ZhaoxiMSA_DelayQueue", true, false, false, args);
|
||||
channel.QueueBind(queue: "ZhaoxiMSA_DelayQueue",
|
||||
exchange: delayExchangeName,
|
||||
routingKey: string.Empty,
|
||||
arguments: null);
|
||||
|
||||
////DLX--- //死信队列绑定
|
||||
//channel.ExchangeDeclare("ZhaoxiMSA_exchange_dlx", "fanout", true, false, null);
|
||||
//channel.QueueDeclare("ZhaoxiMSA_queue_dlx", true, false, false, null);
|
||||
//channel.QueueBind("ZhaoxiMSA_queue_dlx", "ZhaoxiMSA_exchange_dlx", "routingkey", null);
|
||||
|
||||
|
||||
channel.TxSelect();//开启Tx事务---RabbitMQ协议级的事务-----强事务
|
||||
var properties = channel.CreateBasicProperties();
|
||||
|
||||
var body = Encoding.UTF8.GetBytes(message);
|
||||
channel.BasicPublish(exchange: delayExchangeName,
|
||||
routingKey: string.Empty,
|
||||
basicProperties: properties,
|
||||
body: body);
|
||||
channel.TxCommit();//提交
|
||||
Console.WriteLine($" [x] Sent {body.Length}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine(ex.Message);
|
||||
Console.WriteLine($"【{message}】发送到Broker失败!{ex.Message}");
|
||||
channel.TxRollback(); //事务回滚--前面的所有操作就全部作废了。。。。
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#region Receive
|
||||
/// <summary>
|
||||
/// 注册处理动作
|
||||
/// </summary>
|
||||
/// <param name="rabbitMQConsumerMode"></param>
|
||||
/// <param name="func"></param>
|
||||
public void RegistReciveAction(RabbitMQConsumerModel rabbitMQConsumerMode, Func<string, bool> func)
|
||||
{
|
||||
this.InitBindQueue(rabbitMQConsumerMode);
|
||||
|
||||
Task.Run(() =>
|
||||
{
|
||||
using (var channel = _CurrentConnection.CreateModel())
|
||||
{
|
||||
var consumer = new EventingBasicConsumer(channel);
|
||||
channel.BasicQos(0, 0, true);
|
||||
consumer.Received += (sender, ea) =>
|
||||
{
|
||||
string str = Encoding.UTF8.GetString(ea.Body.ToArray());
|
||||
if (func(str))
|
||||
{
|
||||
channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false);//确认已消费
|
||||
}
|
||||
else
|
||||
{
|
||||
//channel.BasicReject(deliveryTag: ea.DeliveryTag, requeue: true);//放回队列--重新包装信息,放入其他队列
|
||||
}
|
||||
};
|
||||
channel.BasicConsume(queue: rabbitMQConsumerMode.QueueName,
|
||||
autoAck: false,//不ACK
|
||||
consumer: consumer);
|
||||
Console.WriteLine($" Register Consumer To {rabbitMQConsumerMode.ExchangeName}-{rabbitMQConsumerMode.QueueName}");
|
||||
Console.ReadLine();
|
||||
Console.WriteLine($" After Register Consumer To {rabbitMQConsumerMode.ExchangeName}-{rabbitMQConsumerMode.QueueName}");
|
||||
}
|
||||
});
|
||||
}
|
||||
#endregion
|
||||
|
||||
}
|
||||
}
|
||||
46
Yi.Framework.Net6/Yi.Framework.Core/SMS/AliyunSMSInvoker.cs
Normal file
@@ -0,0 +1,46 @@
|
||||
using Microsoft.Extensions.Options;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Yi.Framework.Common.IOCOptions;
|
||||
|
||||
namespace Yi.Framework.Core.SMS
|
||||
{
|
||||
public class AliyunSMSInvoker
|
||||
{
|
||||
private IOptionsMonitor<SMSOptions> _sMSOptions;
|
||||
public AliyunSMSInvoker(IOptionsMonitor<SMSOptions> sMSOptions)
|
||||
{
|
||||
_sMSOptions = sMSOptions;
|
||||
}
|
||||
private static AlibabaCloud.SDK.Dysmsapi20170525.Client CreateClient(string accessKeyId, string accessKeySecret)
|
||||
{
|
||||
AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config
|
||||
{
|
||||
// 您的AccessKey ID
|
||||
AccessKeyId = accessKeyId,
|
||||
// 您的AccessKey Secret
|
||||
AccessKeySecret = accessKeySecret,
|
||||
};
|
||||
// 访问的域名
|
||||
config.Endpoint = "dysmsapi.aliyuncs.com";
|
||||
return new AlibabaCloud.SDK.Dysmsapi20170525.Client(config);
|
||||
}
|
||||
|
||||
public void SendCode(string code,string phone)
|
||||
{
|
||||
AlibabaCloud.SDK.Dysmsapi20170525.Client client = CreateClient(_sMSOptions.CurrentValue.ID, _sMSOptions.CurrentValue.Secret);
|
||||
AlibabaCloud.SDK.Dysmsapi20170525.Models.SendSmsRequest sendSmsRequest = new AlibabaCloud.SDK.Dysmsapi20170525.Models.SendSmsRequest
|
||||
{
|
||||
PhoneNumbers = phone,
|
||||
SignName = _sMSOptions.CurrentValue.Sign,
|
||||
TemplateCode = _sMSOptions.CurrentValue.Template,
|
||||
TemplateParam = "{\"code\":\""+ code + "\"}",
|
||||
};
|
||||
// 复制代码运行请自行打印 API 的返回值
|
||||
client.SendSms(sendSmsRequest);
|
||||
}
|
||||
}
|
||||
}
|
||||
108
Yi.Framework.Net6/Yi.Framework.Core/TreeMenuBuild.cs
Normal file
@@ -0,0 +1,108 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Yi.Framework.Model.Models;
|
||||
|
||||
namespace Yi.Framework.Core
|
||||
{
|
||||
public static class TreeMenuBuild
|
||||
{
|
||||
/// <summary>
|
||||
/// 过滤所有已经删除的菜单
|
||||
/// </summary>
|
||||
/// <param name="menu_data"></param>
|
||||
/// <returns></returns>
|
||||
public static menu Normal(menu menu_data)
|
||||
{
|
||||
for (int i = menu_data.children.Count() - 1; i >= 0; i--)
|
||||
{
|
||||
if (menu_data.children[i].is_delete == (short)Common.Enum.DelFlagEnum.Deleted)
|
||||
{
|
||||
menu_data.children.Remove(menu_data.children[i]);
|
||||
}
|
||||
else if (menu_data.children[i] != null)
|
||||
{
|
||||
Normal(menu_data.children[i]);
|
||||
}
|
||||
}
|
||||
return menu_data;
|
||||
}
|
||||
|
||||
|
||||
|
||||
public static menu ShowFormat(menu menu_data, List<int> allMenuIds)
|
||||
{
|
||||
return Format(Show(menu_data, allMenuIds));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 过滤用户不展示及已删除及未拥有的菜单
|
||||
/// </summary>
|
||||
/// <param name="menu_data"></param>
|
||||
/// <param name="allMenuIds"></param>
|
||||
/// <returns></returns>
|
||||
private static menu Show(menu menu_data, List<int> allMenuIds)
|
||||
{
|
||||
for (int i = menu_data.children.Count() - 1; i >= 0; i--)
|
||||
{
|
||||
if (!allMenuIds.Contains(menu_data.children[i].id) || menu_data.children[i].is_delete == (short)Common.Enum.DelFlagEnum.Deleted || menu_data.children[i].is_show == (short)Common.Enum.ShowFlagEnum.NoShow)
|
||||
{
|
||||
menu_data.children.Remove(menu_data.children[i]);
|
||||
}
|
||||
else
|
||||
{
|
||||
Show(menu_data.children[i], allMenuIds);
|
||||
}
|
||||
}
|
||||
return menu_data;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 为了匹配前端格式,通常和show方法一起
|
||||
/// </summary>
|
||||
/// <param name="menu_data"></param>
|
||||
/// <returns></returns>
|
||||
private static menu Format(menu menu_data)
|
||||
{
|
||||
for (int i = menu_data.children.Count() - 1; i >= 0; i--)
|
||||
{
|
||||
if (menu_data.children[i].icon == null)
|
||||
{
|
||||
menu_data.children[i].icon = "mdi-view-dashboard";
|
||||
}
|
||||
if (menu_data.children != null || menu_data.children.Count() != 0)
|
||||
{
|
||||
Format(menu_data.children[i]);
|
||||
}
|
||||
}
|
||||
if (menu_data.children.Count() == 0)
|
||||
{
|
||||
menu_data.children = null;
|
||||
}
|
||||
|
||||
return menu_data;
|
||||
}
|
||||
|
||||
public static menu Sort(menu menu_data)
|
||||
{
|
||||
if (menu_data.children != null)
|
||||
{
|
||||
for (int i = menu_data.children.Count() - 1; i >= 0; i--)
|
||||
{
|
||||
menu_data.children = menu_data.children.AsEnumerable().OrderByDescending(u => u.sort).ToList();
|
||||
|
||||
if (menu_data.children != null || menu_data.children.Count() != 0)
|
||||
{
|
||||
Sort(menu_data.children[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return menu_data;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
43
Yi.Framework.Net6/Yi.Framework.Core/Yi.Framework.Core.csproj
Normal file
@@ -0,0 +1,43 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net6.0</TargetFramework>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AlibabaCloud.SDK.Dysmsapi20170525" Version="2.0.8" />
|
||||
<PackageReference Include="Consul" Version="1.6.10.3" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.1" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.2.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="6.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="6.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Options" Version="6.0.0" />
|
||||
<PackageReference Include="NEST" Version="7.16.0" />
|
||||
<PackageReference Include="RabbitMQ.Client" Version="6.2.2" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Yi.Framework.Common\Yi.Framework.Common.csproj" />
|
||||
<ProjectReference Include="..\Yi.Framework.Model\Yi.Framework.Model.csproj" />
|
||||
<ProjectReference Include="..\Yi.Framework.Task\Yi.Framework.Job.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Reference Include="Microsoft.Bcl.AsyncInterfaces">
|
||||
<HintPath>Library\Microsoft.Bcl.AsyncInterfaces.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="ServiceStack.Common">
|
||||
<HintPath>Library\ServiceStack.Common.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="ServiceStack.Interfaces">
|
||||
<HintPath>Library\ServiceStack.Interfaces.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="ServiceStack.Redis">
|
||||
<HintPath>Library\ServiceStack.Redis.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="ServiceStack.Text">
|
||||
<HintPath>Library\ServiceStack.Text.dll</HintPath>
|
||||
</Reference>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
15
Yi.Framework.Net6/Yi.Framework.DTOModel/ChangePwdDto.cs
Normal file
@@ -0,0 +1,15 @@
|
||||
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; }
|
||||
}
|
||||
}
|
||||
14
Yi.Framework.Net6/Yi.Framework.DTOModel/ChildrenDto.cs
Normal file
@@ -0,0 +1,14 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Yi.Framework.DTOModel
|
||||
{
|
||||
public class ChildrenDto<T>
|
||||
{
|
||||
public int parentId { get; set; }
|
||||
public T data { get; set; }
|
||||
}
|
||||
}
|
||||
23
Yi.Framework.Net6/Yi.Framework.DTOModel/IdsDto.cs
Normal file
@@ -0,0 +1,23 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Yi.Framework.DTOModel
|
||||
{
|
||||
public class IdDto<T>
|
||||
{
|
||||
public T id1 { get; set; }
|
||||
public T id2 { get; set; }
|
||||
}
|
||||
|
||||
public class IdsDto<T>
|
||||
{
|
||||
public T id{ get; set; }
|
||||
public List<T> ids { get; set; }
|
||||
}
|
||||
|
||||
public class IdsListDto<T>
|
||||
{
|
||||
public List<T> ids1 { get; set; }
|
||||
public List<T> ids2 { get; set; }
|
||||
}
|
||||
}
|
||||
16
Yi.Framework.Net6/Yi.Framework.DTOModel/SettingDto.cs
Normal file
@@ -0,0 +1,16 @@
|
||||
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<string> ImageList { get; set; }
|
||||
}
|
||||
}
|
||||