mirror of
https://gitee.com/ccnetcore/Yi
synced 2026-03-16 14:36:37 +08:00
Compare commits
42 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
442ae94ad5 | ||
|
|
43820f71a3 | ||
|
|
63920e034a | ||
|
|
cddc47305f | ||
|
|
583bebd10c | ||
|
|
7fe9a6c900 | ||
|
|
670e457dc6 | ||
|
|
300d8224ec | ||
|
|
924f5320bb | ||
|
|
dd09fb2283 | ||
|
|
3e18af626b | ||
|
|
89dd5b79d6 | ||
|
|
356f71f13e | ||
|
|
2f5d71a299 | ||
|
|
b581c12edb | ||
|
|
d4d6aeb0b4 | ||
|
|
77114e6cfc | ||
|
|
e14a078440 | ||
|
|
3b38a0d628 | ||
|
|
927d8cb6c9 | ||
|
|
eb8ea2f549 | ||
|
|
208c93bc8f | ||
|
|
93180faa23 | ||
|
|
816858f231 | ||
|
|
fa1d68848f | ||
|
|
bce955a1e1 | ||
|
|
82f70e0ac9 | ||
|
|
fc9b78cfef | ||
|
|
72400a48da | ||
|
|
537b39b3c4 | ||
|
|
47e6e48729 | ||
|
|
d252229777 | ||
|
|
7f4c7f607d | ||
|
|
994ba5dd1a | ||
|
|
e3a06b28dd | ||
|
|
10d512470e | ||
|
|
c1d8040fd5 | ||
|
|
e4b81da386 | ||
|
|
fd7360e6f4 | ||
|
|
62f15e218e | ||
|
|
5c1b91f348 | ||
|
|
3994f14010 |
12
README.md
12
README.md
@@ -22,7 +22,9 @@ Yi框架-一套与SqlSugar一样爽的.Net6低代码开源框架。
|
|||||||
适合.Net6学习、Sqlsugar学习 、项目二次开发。
|
适合.Net6学习、Sqlsugar学习 、项目二次开发。
|
||||||
集大成者,终究轮子
|
集大成者,终究轮子
|
||||||
|
|
||||||
Yi框架最新版本标签:`v1.1.2`,具体版本可以查看标签迭代
|
|
||||||
|
Yi框架最新版本标签:`v1.2.0`,具体版本可以查看标签迭代
|
||||||
|
|
||||||
|
|
||||||
(项目与Sqlsugar同步更新,但这作者老杰哥代码天天爆肝到凌晨两点,我们也尽量会跟上他的脚步。更新频繁,所以可watching持续关注。)
|
(项目与Sqlsugar同步更新,但这作者老杰哥代码天天爆肝到凌晨两点,我们也尽量会跟上他的脚步。更新频繁,所以可watching持续关注。)
|
||||||
|
|
||||||
@@ -74,7 +76,7 @@ WebFirst开发:所有代码生成器已经配置完成,无需任何操作数
|
|||||||
|
|
||||||
**身份验证**:JWT、IdentityServer4
|
**身份验证**:JWT、IdentityServer4
|
||||||
|
|
||||||
**组件**:~~EFcore~~SqlSugar、Autofac、Castle、Swagger、Log4Net、Redis、RabbitMq、ES、Quartz.net、~~T4~~
|
**组件**:SqlSugar、Autofac、Castle、Swagger、Log4Net、Redis、RabbitMq、ES、Quartz.net、~~T4~~
|
||||||
|
|
||||||
**分布式**:CAP、Lock
|
**分布式**:CAP、Lock
|
||||||
|
|
||||||
@@ -96,9 +98,8 @@ WebFirst开发:所有代码生成器已经配置完成,无需任何操作数
|
|||||||
- [x] 支持采用`异步`开发awit/async
|
- [x] 支持采用`异步`开发awit/async
|
||||||
- [x] 支持数据库主从`读写分离`
|
- [x] 支持数据库主从`读写分离`
|
||||||
- [x] 支持功能替换,无需改动代码,只需配置`json文件`进行装配即可
|
- [x] 支持功能替换,无需改动代码,只需配置`json文件`进行装配即可
|
||||||
- [x] ~~-支持采用DbFirst开发方式,使用`T4模板代码生成器`,自动映射模型一键生成Service及IService所有代码~~
|
|
||||||
- [x] 支持WebFirst,无需改动代码,自动生成全套代码与数据库,只需点点点
|
- [x] 支持WebFirst,无需改动代码,自动生成全套代码与数据库,只需点点点
|
||||||
- [x] ~~-支持`用户-角色-菜单-接口`以及vue2.0前端全部逻辑代码,下载无需修改直接使用~~
|
- [x] 支持`用户-角色-菜单-接口`以及vue2.0前端全部逻辑代码,下载无需修改直接使用
|
||||||
- [x] 支持`Aop封装`,FilterAop、IocAop、LogAop、SqlAop
|
- [x] 支持`Aop封装`,FilterAop、IocAop、LogAop、SqlAop
|
||||||
- [x] 支持`Log4Net日志`记录,自动生成至bin目录下的logs文件夹
|
- [x] 支持`Log4Net日志`记录,自动生成至bin目录下的logs文件夹
|
||||||
- [x] 支持`DbSeed数据库种子数据`接入
|
- [x] 支持`DbSeed数据库种子数据`接入
|
||||||
@@ -114,7 +115,6 @@ WebFirst开发:所有代码生成器已经配置完成,无需任何操作数
|
|||||||
- [x] 支持`Ocelot`网关,路由、服务聚合、服务发现、认证、鉴权、限流、熔断、缓存、Header头传递
|
- [x] 支持`Ocelot`网关,路由、服务聚合、服务发现、认证、鉴权、限流、熔断、缓存、Header头传递
|
||||||
- [x] 支持`Apollo`全局配置中心;
|
- [x] 支持`Apollo`全局配置中心;
|
||||||
- [x] 支持`docker`镜像制作
|
- [x] 支持`docker`镜像制作
|
||||||
- [x] ~~-支持页面`静态化处理`,将动态页面生成静态页面~~
|
|
||||||
- [x] 支持`Quartz.net`任务调度,实现任意接口被调度
|
- [x] 支持`Quartz.net`任务调度,实现任意接口被调度
|
||||||
- [x] 支持`ELK`,log4net+kafka+es+logstach+kibana
|
- [x] 支持`ELK`,log4net+kafka+es+logstach+kibana
|
||||||
- [x] 支持`IdentityService4`授权中心
|
- [x] 支持`IdentityService4`授权中心
|
||||||
@@ -124,7 +124,7 @@ WebFirst开发:所有代码生成器已经配置完成,无需任何操作数
|
|||||||
- [x] 支持`Docker+k8s`部署
|
- [x] 支持`Docker+k8s`部署
|
||||||
- [x] 支持`Jenkins+CI/CD`
|
- [x] 支持`Jenkins+CI/CD`
|
||||||
- [x] 支持`AutoMapper`模块映射
|
- [x] 支持`AutoMapper`模块映射
|
||||||
- [ ] 支持`微信支付`(没账号)
|
- [x] 支持`微信支付`
|
||||||
- [x] 支持`单表多租户`常用功能
|
- [x] 支持`单表多租户`常用功能
|
||||||
- [x] 支持`逻辑删除`常用功能
|
- [x] 支持`逻辑删除`常用功能
|
||||||
- [x] 支持`操作日志`常用功能
|
- [x] 支持`操作日志`常用功能
|
||||||
|
|||||||
Binary file not shown.
@@ -23,6 +23,12 @@
|
|||||||
<param name="registerDto"></param>
|
<param name="registerDto"></param>
|
||||||
<returns></returns>
|
<returns></returns>
|
||||||
</member>
|
</member>
|
||||||
|
<member name="M:Yi.Framework.ApiMicroservice.Controllers.AccountController.Logout">
|
||||||
|
<summary>
|
||||||
|
没啥说,登出
|
||||||
|
</summary>
|
||||||
|
<returns></returns>
|
||||||
|
</member>
|
||||||
<member name="M:Yi.Framework.ApiMicroservice.Controllers.AccountController.GetUserAllInfo">
|
<member name="M:Yi.Framework.ApiMicroservice.Controllers.AccountController.GetUserAllInfo">
|
||||||
<summary>
|
<summary>
|
||||||
通过已登录的用户获取用户信息及菜单
|
通过已登录的用户获取用户信息及菜单
|
||||||
|
|||||||
@@ -47,7 +47,8 @@ namespace Yi.Framework.ApiMicroservice.Controllers
|
|||||||
UserEntity user = new();
|
UserEntity user = new();
|
||||||
if (await _iUserService.Login(loginDto.UserName, loginDto.Password, o => user = o))
|
if (await _iUserService.Login(loginDto.UserName, loginDto.Password, o => user = o))
|
||||||
{
|
{
|
||||||
return Result.Success("登录成功!").SetData(new { token = _jwtInvoker.GetAccessToken(user) });
|
var userRoleMenu= await _iUserService.GetUserAllInfo(user.Id);
|
||||||
|
return Result.Success("登录成功!").SetData(new { token = _jwtInvoker.GetAccessToken(userRoleMenu.User,userRoleMenu.Menus) });
|
||||||
}
|
}
|
||||||
return Result.SuccessError("登录失败!用户名或者密码错误!");
|
return Result.SuccessError("登录失败!用户名或者密码错误!");
|
||||||
}
|
}
|
||||||
@@ -69,6 +70,10 @@ namespace Yi.Framework.ApiMicroservice.Controllers
|
|||||||
return Result.SuccessError("注册失败!用户名已存在!");
|
return Result.SuccessError("注册失败!用户名已存在!");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 没啥说,登出
|
||||||
|
/// </summary>
|
||||||
|
/// <returns></returns>
|
||||||
[HttpPost]
|
[HttpPost]
|
||||||
public Result Logout()
|
public Result Logout()
|
||||||
{
|
{
|
||||||
@@ -80,6 +85,7 @@ namespace Yi.Framework.ApiMicroservice.Controllers
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
[HttpGet]
|
[HttpGet]
|
||||||
|
[Authorize]
|
||||||
public async Task<Result> GetUserAllInfo()
|
public async Task<Result> GetUserAllInfo()
|
||||||
{
|
{
|
||||||
//通过鉴权jwt获取到用户的id
|
//通过鉴权jwt获取到用户的id
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ namespace Yi.Framework.ApiMicroservice.Controllers
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="id"></param>
|
/// <param name="id"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
[Permission($"{nameof(T)}:get:one")]
|
[Permission($"{nameof(T)}:get")]
|
||||||
[HttpGet]
|
[HttpGet]
|
||||||
public virtual async Task<Result> GetById(long id)
|
public virtual async Task<Result> GetById(long id)
|
||||||
{
|
{
|
||||||
@@ -43,7 +43,7 @@ namespace Yi.Framework.ApiMicroservice.Controllers
|
|||||||
/// 列表查询
|
/// 列表查询
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
[Permission($"{nameof(T)}:get:list")]
|
[Permission($"{nameof(T)}:get")]
|
||||||
[HttpPost]
|
[HttpPost]
|
||||||
public virtual async Task<Result> GetList(QueryCondition queryCondition)
|
public virtual async Task<Result> GetList(QueryCondition queryCondition)
|
||||||
{
|
{
|
||||||
@@ -55,7 +55,7 @@ namespace Yi.Framework.ApiMicroservice.Controllers
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="queryCondition"></param>
|
/// <param name="queryCondition"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
[Permission($"{nameof(T)}:get:page")]
|
[Permission($"{nameof(T)}:get")]
|
||||||
[HttpPost]
|
[HttpPost]
|
||||||
public virtual async Task<Result> PageList(QueryPageCondition queryCondition)
|
public virtual async Task<Result> PageList(QueryPageCondition queryCondition)
|
||||||
{
|
{
|
||||||
@@ -91,7 +91,7 @@ namespace Yi.Framework.ApiMicroservice.Controllers
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="ids"></param>
|
/// <param name="ids"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
[Permission($"{nameof(T)}:delete:list")]
|
[Permission($"{nameof(T)}:del")]
|
||||||
[HttpDelete]
|
[HttpDelete]
|
||||||
public virtual async Task<Result> DeleteList(List<long> ids)
|
public virtual async Task<Result> DeleteList(List<long> ids)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -45,7 +45,7 @@ namespace Yi.Framework.ApiMicroservice.Controllers
|
|||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
[HttpGet]
|
[HttpGet]
|
||||||
// 特点:化繁为简!意框架仓储代理上下文对象,用起来就是爽,但最好按规范来爽!
|
// 特点:化繁为简!意框架仓储代理上下文对象,用起来就是爽,但最好按规范来爽!
|
||||||
// 规范:控制器不建议使用切换仓储方法、控制器严禁使用DB上下文对象,其它怎么爽怎么来!
|
// 规范:控制器严禁使用DB上下文对象,其它怎么爽怎么来!
|
||||||
public async Task<Result> DbTest()
|
public async Task<Result> DbTest()
|
||||||
{
|
{
|
||||||
//非常好,使用UserService的特有方法
|
//非常好,使用UserService的特有方法
|
||||||
@@ -60,7 +60,7 @@ namespace Yi.Framework.ApiMicroservice.Controllers
|
|||||||
//挺不错,依赖注入其他仓储
|
//挺不错,依赖注入其他仓储
|
||||||
await _iRoleService._repository.GetListAsync();
|
await _iRoleService._repository.GetListAsync();
|
||||||
|
|
||||||
//不建议操作,直接切换其他仓储
|
//还行,直接切换其他仓储,怎么爽怎么来
|
||||||
await _iUserService._repository.ChangeRepository<Repository<RoleEntity>>().GetListAsync();
|
await _iUserService._repository.ChangeRepository<Repository<RoleEntity>>().GetListAsync();
|
||||||
|
|
||||||
//最好不要直接操作Db对象
|
//最好不要直接操作Db对象
|
||||||
@@ -74,7 +74,7 @@ namespace Yi.Framework.ApiMicroservice.Controllers
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
[HttpGet]
|
[HttpGet]
|
||||||
//简单语句不推荐!
|
//简单语句不推荐使用sql!
|
||||||
public async Task<Result> SqlTest()
|
public async Task<Result> SqlTest()
|
||||||
{
|
{
|
||||||
return Result.Success().SetData(await _iUserService._repository.UseSqlAsync<UserEntity>("select * from User"));
|
return Result.Success().SetData(await _iUserService._repository.UseSqlAsync<UserEntity>("select * from User"));
|
||||||
@@ -165,7 +165,7 @@ namespace Yi.Framework.ApiMicroservice.Controllers
|
|||||||
{JobConst.method,"get" },
|
{JobConst.method,"get" },
|
||||||
{JobConst.url,"https://www.baidu.com" }
|
{JobConst.url,"https://www.baidu.com" }
|
||||||
};
|
};
|
||||||
await _quartzInvoker.start("*/5 * * * * ?", new Quartz.JobKey("test", "my"), "Yi.Framework.Job", "HttpJob", data: data);
|
await _quartzInvoker.StartAsync("*/5 * * * * ?", "HttpJob",jobName:"test",jobGroup:"my", data: data);
|
||||||
return Result.Success();
|
return Result.Success();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -176,7 +176,7 @@ namespace Yi.Framework.ApiMicroservice.Controllers
|
|||||||
[HttpPut]
|
[HttpPut]
|
||||||
public async Task<Result> stopJob()
|
public async Task<Result> stopJob()
|
||||||
{
|
{
|
||||||
await _quartzInvoker.Stop(new Quartz.JobKey("test", "my"));
|
await _quartzInvoker.StopAsync(new Quartz.JobKey("test", "my"));
|
||||||
return Result.Success();
|
return Result.Success();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,10 +21,16 @@
|
|||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ProjectReference Include="..\Yi.Framework.DTOModel\Yi.Framework.DTOModel.csproj" />
|
<None Remove="yi-sqlsugar-dev.db" />
|
||||||
<ProjectReference Include="..\Yi.Framework.Interface\Yi.Framework.Interface.csproj" />
|
</ItemGroup>
|
||||||
<ProjectReference Include="..\Yi.Framework.Model\Yi.Framework.Model.csproj" />
|
|
||||||
<ProjectReference Include="..\Yi.Framework.Service\Yi.Framework.Service.csproj" />
|
<ItemGroup>
|
||||||
|
<Content Include="yi-sqlsugar-dev.db">
|
||||||
|
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||||
|
</Content>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
<ProjectReference Include="..\Yi.Framework.WebCore\Yi.Framework.WebCore.csproj" />
|
<ProjectReference Include="..\Yi.Framework.WebCore\Yi.Framework.WebCore.csproj" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
{
|
{
|
||||||
"StartUrl": "http://localohost:19001",
|
"StartUrl": "http://*:19001",
|
||||||
"Logging": {
|
"Logging": {
|
||||||
"LogLevel": {
|
"LogLevel": {
|
||||||
"Default": "Information",
|
"Default": "Information",
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
{
|
{
|
||||||
"StartUrl": "http://localohost:19001",
|
"StartUrl": "http://*:19001",
|
||||||
"Logging": {
|
"Logging": {
|
||||||
"LogLevel": {
|
"LogLevel": {
|
||||||
"Default": "Information",
|
"Default": "Information",
|
||||||
|
|||||||
Binary file not shown.
430
Yi.Framework.Net6/Yi.Framework.Common/Base/NullValue.cs
Normal file
430
Yi.Framework.Net6/Yi.Framework.Common/Base/NullValue.cs
Normal file
@@ -0,0 +1,430 @@
|
|||||||
|
namespace System
|
||||||
|
{
|
||||||
|
#region 无值定义
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 无值定义
|
||||||
|
/// </summary>
|
||||||
|
public class NullValue
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 唯一识别型的默认无值
|
||||||
|
/// </summary>
|
||||||
|
public static readonly Guid Guid = Guid.Empty;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 日期时间的默认无值
|
||||||
|
/// </summary>
|
||||||
|
/// <remarks>解决C#DateTime最小值是SQL 2005不允许的范围内</remarks>
|
||||||
|
public static readonly DateTime DateTime = DateTime.Parse("1753-1-1 12:00:01");
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// JavaScript日期时间的默认无值
|
||||||
|
/// </summary>
|
||||||
|
/// <remarks></remarks>
|
||||||
|
public static readonly DateTime JavaScriptDateTime = DateTime.Parse("1970-1-1 00:00:00");
|
||||||
|
|
||||||
|
#region 数字类型
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 短整数的默认无值
|
||||||
|
/// </summary>
|
||||||
|
public const short ShortInterger = -1;//short.MinValue;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 整数的默认无值
|
||||||
|
/// </summary>
|
||||||
|
public const int Interger = -1;//int.MinValue;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 长整数的默认无值
|
||||||
|
/// </summary>
|
||||||
|
public const long LongInterger = -1;//long.MinValue;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Decimal数的默认无值
|
||||||
|
/// </summary>
|
||||||
|
public const decimal Decimal = -1;//decimal.MinValue;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Float数的默认无值
|
||||||
|
/// </summary>
|
||||||
|
public const float Float = -1;//float.MinValue;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Double数的默认无值
|
||||||
|
/// </summary>
|
||||||
|
public const double Double = -1;//double.MinValue;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Byte数的默认无值
|
||||||
|
/// </summary>
|
||||||
|
public const byte Byte = byte.MinValue;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// SByte数的默认无值
|
||||||
|
/// </summary>
|
||||||
|
public const sbyte SByte = sbyte.MinValue;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 字串的默认无值
|
||||||
|
/// </summary>
|
||||||
|
public static readonly string String = String.Empty;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 一般对象的判断
|
||||||
|
/// </summary>
|
||||||
|
public const Object Object = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region 无值的扩展方法
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 无值的扩展方法
|
||||||
|
/// </summary>
|
||||||
|
public static class NullValueExtensions
|
||||||
|
{
|
||||||
|
#region 一般类型
|
||||||
|
|
||||||
|
public static Guid TryToGuid(this string guid)
|
||||||
|
{
|
||||||
|
if (Guid.TryParse(guid, out var guid1))
|
||||||
|
{
|
||||||
|
return guid1;
|
||||||
|
}
|
||||||
|
return Guid.Empty;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public static string TryStringNull(this string value)
|
||||||
|
{
|
||||||
|
return value == null ? "" : value;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Object类型无值判断
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="value">待判断对象</param>
|
||||||
|
/// <returns>是否为空(true--真,false--假)</returns>
|
||||||
|
public static bool IsNull(this object value)
|
||||||
|
{
|
||||||
|
if (value == null || value == NullValue.Object)
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Object类型有值判断
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="value">待判断对象</param>
|
||||||
|
/// <returns>是否不为空(true--真,false--假)</returns>
|
||||||
|
public static bool IsNotNull(this object value)
|
||||||
|
{
|
||||||
|
return !value.IsNull();
|
||||||
|
}
|
||||||
|
public static bool IsGuidNotNull(this Guid? value)
|
||||||
|
{
|
||||||
|
return !value.IsGuidNull();
|
||||||
|
}
|
||||||
|
public static bool IsGuidNull(this Guid? value)
|
||||||
|
{
|
||||||
|
if (value == null || value == Guid.Empty)
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
/// <summary>
|
||||||
|
/// String类型无值判断
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="value">待判断对象</param>
|
||||||
|
/// <returns>是否为空(true--真,false--假)</returns>
|
||||||
|
public static bool IsNull(this String value)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(value) || string.IsNullOrWhiteSpace(value))
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// String类型有值判断
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="value">待判断对象</param>
|
||||||
|
/// <returns>是否不为空(true--真,false--假)</returns>
|
||||||
|
public static bool IsNotNull(this String value)
|
||||||
|
{
|
||||||
|
return !value.IsNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Guid类型无值判断
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="value">待判断对象</param>
|
||||||
|
/// <returns>是否为空(true--真,false--假)</returns>
|
||||||
|
public static bool IsNull(this Guid value)
|
||||||
|
{
|
||||||
|
if (value == NullValue.Guid)
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Guid类型有值判断
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="value">待判断对象</param>
|
||||||
|
/// <returns>是否不为空(true--真,false--假)</returns>
|
||||||
|
public static bool IsNotNull(this Guid value)
|
||||||
|
{
|
||||||
|
return !value.IsNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
#region 数字类型
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// ShortInterger类型无值判断
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="value">待判断对象</param>
|
||||||
|
/// <returns>是否为空(true--真,false--假)</returns>
|
||||||
|
public static bool IsNull(this short value)
|
||||||
|
{
|
||||||
|
if (value == NullValue.ShortInterger)
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// ShortInterger类型有值判断
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="value">待判断对象</param>
|
||||||
|
/// <returns>是否不为空(true--真,false--假)</returns>
|
||||||
|
public static bool IsNotNull(this short value)
|
||||||
|
{
|
||||||
|
return !value.IsNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Interger类型无值判断
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="value">待判断对象</param>
|
||||||
|
/// <returns>是否为空(true--真,false--假)</returns>
|
||||||
|
public static bool IsNull(this int value)
|
||||||
|
{
|
||||||
|
if (value == NullValue.Interger)
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Interger类型有值判断
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="value">待判断对象</param>
|
||||||
|
/// <returns>是否不为空(true--真,false--假)</returns>
|
||||||
|
public static bool IsNotNull(this int value)
|
||||||
|
{
|
||||||
|
return !value.IsNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// LongInterger类型无值判断
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="value">待判断对象</param>
|
||||||
|
/// <returns>是否为空(true--真,false--假)</returns>
|
||||||
|
public static bool IsNull(this long value)
|
||||||
|
{
|
||||||
|
if (value == NullValue.LongInterger)
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// LongInterger类型有值判断
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="value">待判断对象</param>
|
||||||
|
/// <returns>是否不为空(true--真,false--假)</returns>
|
||||||
|
public static bool IsNotNull(this long value)
|
||||||
|
{
|
||||||
|
return !value.IsNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Decimal类型无值判断
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="value">待判断对象</param>
|
||||||
|
/// <returns>是否为空(true--真,false--假)</returns>
|
||||||
|
public static bool IsNull(this decimal value)
|
||||||
|
{
|
||||||
|
if (value == NullValue.Decimal)
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Decimal类型有值判断
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="value">待判断对象</param>
|
||||||
|
/// <returns>是否不为空(true--真,false--假)</returns>
|
||||||
|
public static bool IsNotNull(this decimal value)
|
||||||
|
{
|
||||||
|
return !value.IsNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Float类型无值判断
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="value">待判断对象</param>
|
||||||
|
/// <returns>是否为空(true--真,false--假)</returns>
|
||||||
|
public static bool IsNull(this float value)
|
||||||
|
{
|
||||||
|
if (value == NullValue.Float)
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Float类型有值判断
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="value">待判断对象</param>
|
||||||
|
/// <returns>是否不为空(true--真,false--假)</returns>
|
||||||
|
public static bool IsNotNull(this float value)
|
||||||
|
{
|
||||||
|
return !value.IsNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Double类型无值判断
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="value">待判断对象</param>
|
||||||
|
/// <returns>是否为空(true--真,false--假)</returns>
|
||||||
|
public static bool IsNull(this double value)
|
||||||
|
{
|
||||||
|
if (value == NullValue.Double)
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Double类型有值判断
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="value">待判断对象</param>
|
||||||
|
/// <returns>是否不为空(true--真,false--假)</returns>
|
||||||
|
public static bool IsNotNull(this double value)
|
||||||
|
{
|
||||||
|
return !value.IsNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Byte类型无值判断
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="value">待判断对象</param>
|
||||||
|
/// <returns>是否为空(true--真,false--假)</returns>
|
||||||
|
public static bool IsNull(this byte value)
|
||||||
|
{
|
||||||
|
if (value == NullValue.Byte)
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Byte类型有值判断
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="value">待判断对象</param>
|
||||||
|
/// <returns>是否不为空(true--真,false--假)</returns>
|
||||||
|
public static bool IsNotNull(this byte value)
|
||||||
|
{
|
||||||
|
return !value.IsNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// SByte类型无值判断
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="value">待判断对象</param>
|
||||||
|
/// <returns>是否为空(true--真,false--假)</returns>
|
||||||
|
public static bool IsNull(this sbyte value)
|
||||||
|
{
|
||||||
|
if (value == NullValue.SByte)
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// SByte类型有值判断
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="value">待判断对象</param>
|
||||||
|
/// <returns>是否不为空(true--真,false--假)</returns>
|
||||||
|
public static bool IsNotNull(this sbyte value)
|
||||||
|
{
|
||||||
|
return !value.IsNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// DateTime类型无值判断
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="value">待判断对象</param>
|
||||||
|
/// <returns>是否为空(true--真,false--假)</returns>
|
||||||
|
public static bool IsNull(this DateTime value)
|
||||||
|
{
|
||||||
|
if (value == DateTime.MinValue || value <= NullValue.DateTime || value == NullValue.JavaScriptDateTime)
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// DateTime类型有值判断
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="value">待判断对象</param>
|
||||||
|
/// <returns>是否不为空(true--真,false--假)</returns>
|
||||||
|
public static bool IsNotNull(this DateTime value)
|
||||||
|
{
|
||||||
|
return !value.IsNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace Yi.Framework.Common.Helper
|
||||||
|
{
|
||||||
|
public class Compare<T, C> : IEqualityComparer<T>
|
||||||
|
{
|
||||||
|
private Func<T, C> _getField;
|
||||||
|
public Compare(Func<T, C> getfield)
|
||||||
|
{
|
||||||
|
this._getField = getfield;
|
||||||
|
}
|
||||||
|
public bool Equals(T x, T y)
|
||||||
|
{
|
||||||
|
return EqualityComparer<C>.Default.Equals(_getField(x), _getField(y));
|
||||||
|
}
|
||||||
|
public int GetHashCode(T obj)
|
||||||
|
{
|
||||||
|
return EqualityComparer<C>.Default.GetHashCode(this._getField(obj));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
public static class DistinctHelper
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 自定义Distinct扩展方法
|
||||||
|
/// </summary>
|
||||||
|
/// <typeparam name="T">要去重的对象类</typeparam>
|
||||||
|
/// <typeparam name="C">自定义去重的字段类型</typeparam>
|
||||||
|
/// <param name="source">要去重的对象</param>
|
||||||
|
/// <param name="getfield">获取自定义去重字段的委托</param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public static IEnumerable<T> DistinctNew<T, C>(this IEnumerable<T> source, Func<T, C> getfield)
|
||||||
|
{
|
||||||
|
return source.Distinct(new Compare<T, C>(getfield));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,60 +1,222 @@
|
|||||||
using System;
|
using OfficeOpenXml;
|
||||||
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.IO;
|
using System.IO;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
|
using System.Reflection;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using OfficeOpenXml;
|
|
||||||
|
|
||||||
namespace Yi.Framework.Common.Helper
|
namespace Yi.Framework.Common.Helper
|
||||||
{
|
{
|
||||||
public class ExcelHelper
|
public class ExcelHelper
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
///
|
/// 导出Excel
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <typeparam name="T"></typeparam>
|
/// <typeparam name="T"></typeparam>
|
||||||
/// <param name="dataList">数据</param>
|
/// <param name="list"></param>
|
||||||
/// <param name="headers">表头</param>
|
/// <param name="sheetName"></param>
|
||||||
/// <returns></returns>
|
/// <param name="fileName"></param>
|
||||||
public static string CreateExcelFromList<T>(List<T> dataList, List<string> headers,string evn)
|
public static string ExportExcel<T>(List<T> list, string sheetName, string fileName,string path)
|
||||||
{
|
{
|
||||||
|
string sFileName = $"{fileName}.xlsx";
|
||||||
|
string newFileName = Path.Combine(path, sFileName);
|
||||||
|
//调试模式需要加上
|
||||||
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
|
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
|
||||||
string sWebRootFolder = Path.Combine($"{evn}", "wwwroot/Excel");//如果用浏览器url下载的方式 存放excel的文件夹一定要建在网站首页的同级目录下!!!
|
Directory.CreateDirectory(Path.GetDirectoryName(newFileName)!);
|
||||||
if (!Directory.Exists(sWebRootFolder))
|
using (ExcelPackage package = new(new FileInfo(newFileName)))
|
||||||
{
|
{
|
||||||
Directory.CreateDirectory(sWebRootFolder);
|
// 添加worksheet
|
||||||
}
|
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(sheetName);
|
||||||
string sFileName = $@"Excel_{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx";
|
//单元格自动适应大小
|
||||||
var path = Path.Combine(sWebRootFolder, sFileName);
|
worksheet.Cells.Style.ShrinkToFit = true;
|
||||||
FileInfo file = new FileInfo(path);
|
//全部字段导出
|
||||||
if (file.Exists)
|
worksheet.Cells.LoadFromCollection(list, true, OfficeOpenXml.Table.TableStyles.Light13);
|
||||||
{
|
|
||||||
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();
|
package.Save();
|
||||||
}
|
}
|
||||||
//return path;//这是返回文件的方式
|
|
||||||
return sFileName; //如果用浏览器url下载的方式 这里直接返回生成的文件名就可以了
|
return newFileName;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 下载导入模板
|
||||||
|
/// </summary>
|
||||||
|
/// <typeparam name="T"></typeparam>
|
||||||
|
/// <param name="list"></param>
|
||||||
|
/// <param name="stream"></param>
|
||||||
|
/// <param name="fileName">下载文件名</param>
|
||||||
|
/// <returns></returns>
|
||||||
|
protected string DownloadImportTemplate<T>(List<T> list, Stream stream, string fileName,string path)
|
||||||
|
{
|
||||||
|
string sFileName = $"{fileName}.xlsx";
|
||||||
|
string newFileName = Path.Combine(path, sFileName);
|
||||||
|
//调试模式需要加上
|
||||||
|
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
|
||||||
|
if (!Directory.Exists(newFileName))
|
||||||
|
{
|
||||||
|
Directory.CreateDirectory(Path.GetDirectoryName(newFileName)!);
|
||||||
|
}
|
||||||
|
using (ExcelPackage package = new(new FileInfo(newFileName)))
|
||||||
|
{
|
||||||
|
// 添加worksheet
|
||||||
|
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(fileName);
|
||||||
|
//单元格自动适应大小
|
||||||
|
worksheet.Cells.Style.ShrinkToFit = true;
|
||||||
|
//全部字段导出
|
||||||
|
worksheet.Cells.LoadFromCollection(list, true, OfficeOpenXml.Table.TableStyles.Light13);
|
||||||
|
package.SaveAs(stream);
|
||||||
|
}
|
||||||
|
|
||||||
|
return sFileName;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 导入数据
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="stream"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public static List<T> ImportData<T>(Stream stream) where T : new()
|
||||||
|
{
|
||||||
|
using ExcelPackage package = new(stream);
|
||||||
|
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
|
||||||
|
ExcelWorksheet worksheet = package.Workbook.Worksheets[0];//读取第1个sheet
|
||||||
|
//获取表格的列数和行数
|
||||||
|
|
||||||
|
int colStart = worksheet.Dimension.Start.Column;
|
||||||
|
int colEnd = worksheet.Dimension.End.Column;
|
||||||
|
int rowStart = worksheet.Dimension.Start.Row;
|
||||||
|
int rowEnd = worksheet.Dimension.End.Row;
|
||||||
|
//int rowCount = worksheet.Dimension.Rows;
|
||||||
|
//int ColCount = worksheet.Dimension.Columns;
|
||||||
|
|
||||||
|
List<T> resultList = new();
|
||||||
|
List<PropertyInfo> propertyInfos = new();// new(typeof(T).GetProperties());
|
||||||
|
Dictionary<string, int> dictHeader = new();
|
||||||
|
for (int i = colStart; i < colEnd; i++)
|
||||||
|
{
|
||||||
|
var name = worksheet.Cells[rowStart, i].Value.ToString();
|
||||||
|
dictHeader[name!] = i;
|
||||||
|
|
||||||
|
PropertyInfo propertyInfo = MapPropertyInfo<T>(name!);
|
||||||
|
if (propertyInfo != null)
|
||||||
|
{
|
||||||
|
propertyInfos.Add(propertyInfo);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (int row = rowStart + 1; row <= rowEnd; row++)
|
||||||
|
{
|
||||||
|
T result = new();
|
||||||
|
|
||||||
|
foreach (PropertyInfo p in propertyInfos)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
ExcelRange cell = worksheet.Cells[row, dictHeader[p.Name]];
|
||||||
|
if (cell.Value == null)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
switch (p.PropertyType.Name.ToLower())
|
||||||
|
{
|
||||||
|
case "string":
|
||||||
|
p.SetValue(result, cell.GetValue<string>());
|
||||||
|
break;
|
||||||
|
case "int16":
|
||||||
|
p.SetValue(result, cell.GetValue<short>()); break;
|
||||||
|
case "int32":
|
||||||
|
p.SetValue(result, cell.GetValue<int>()); break;
|
||||||
|
case "int64":
|
||||||
|
p.SetValue(result, cell.GetValue<long>()); break;
|
||||||
|
case "decimal":
|
||||||
|
p.SetValue(result, cell.GetValue<decimal>());
|
||||||
|
break;
|
||||||
|
case "double":
|
||||||
|
p.SetValue(result, cell.GetValue<double>()); break;
|
||||||
|
case "datetime":
|
||||||
|
p.SetValue(result, cell.GetValue<DateTime>()); break;
|
||||||
|
case "boolean":
|
||||||
|
p.SetValue(result, cell.GetValue<bool>()); break;
|
||||||
|
case "char":
|
||||||
|
p.SetValue(result, cell.GetValue<string>()); break;
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (KeyNotFoundException ex)
|
||||||
|
{
|
||||||
|
Console.WriteLine("未找到该列将继续循环," + ex.Message);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
resultList.Add(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
return resultList.ToList();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 查找Excel列名对应的实体属性
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="columnName"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
private static PropertyInfo MapPropertyInfo<T>(string columnName)
|
||||||
|
{
|
||||||
|
PropertyInfo[] propertyList = GetProperties(typeof(T));
|
||||||
|
PropertyInfo propertyInfo = propertyList.Where(p => p.Name == columnName).FirstOrDefault()!;
|
||||||
|
if (propertyInfo != null)
|
||||||
|
{
|
||||||
|
return propertyInfo;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
foreach (PropertyInfo tempPropertyInfo in propertyList)
|
||||||
|
{
|
||||||
|
System.ComponentModel.DescriptionAttribute[] attributes = (System.ComponentModel.DescriptionAttribute[])tempPropertyInfo.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false);
|
||||||
|
if (attributes.Length > 0)
|
||||||
|
{
|
||||||
|
if (attributes[0].Description == columnName)
|
||||||
|
{
|
||||||
|
return tempPropertyInfo;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null!;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 得到类里面的属性集合
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="type"></param>
|
||||||
|
/// <param name="columns"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
private static PropertyInfo[] GetProperties(Type type, string[] columns = null!)
|
||||||
|
{
|
||||||
|
PropertyInfo[] properties = null!;
|
||||||
|
properties = type.GetProperties();
|
||||||
|
|
||||||
|
if (columns != null && columns.Length > 0)
|
||||||
|
{
|
||||||
|
// 按columns顺序返回属性
|
||||||
|
var columnPropertyList = new List<PropertyInfo>();
|
||||||
|
foreach (var column in columns)
|
||||||
|
{
|
||||||
|
var columnProperty = properties.Where(p => p.Name == column).FirstOrDefault();
|
||||||
|
if (columnProperty != null)
|
||||||
|
{
|
||||||
|
columnPropertyList.Add(columnProperty);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return columnPropertyList.ToArray();
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
return properties;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
397
Yi.Framework.Net6/Yi.Framework.Common/Helper/ZipHelper.cs
Normal file
397
Yi.Framework.Net6/Yi.Framework.Common/Helper/ZipHelper.cs
Normal file
@@ -0,0 +1,397 @@
|
|||||||
|
/***
|
||||||
|
* Title:"基础工具" 项目
|
||||||
|
* Title:"基础工具" 项目
|
||||||
|
* 主题:压缩包帮助类
|
||||||
|
* Description:
|
||||||
|
* 功能:
|
||||||
|
* 1、压缩单个文件
|
||||||
|
* 2、压缩多个文件
|
||||||
|
* 3、压缩多层目录
|
||||||
|
* 4、递归遍历目录
|
||||||
|
* 5、解压缩一个 zip 文件
|
||||||
|
* 6、获取压缩文件中指定类型的文件
|
||||||
|
* 7、获取压缩文件中的所有文件
|
||||||
|
* Date:2021
|
||||||
|
* Version:0.1版本
|
||||||
|
* Author:Coffee
|
||||||
|
* Modify Recoder:
|
||||||
|
*/
|
||||||
|
|
||||||
|
using ICSharpCode.SharpZipLib.Zip;
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.IO;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace Yi.Framework.Common.Helper
|
||||||
|
{
|
||||||
|
public class ZipHelper
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 压缩单个文件
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="fileToZip">要压缩的文件</param>
|
||||||
|
/// <param name="zipedFile">压缩后的文件</param>
|
||||||
|
/// <param name="compressionLevel">压缩等级</param>
|
||||||
|
/// <param name="blockSize">每次写入大小</param>
|
||||||
|
public static void ZipFile(string fileToZip, string zipedFile, int compressionLevel, int blockSize)
|
||||||
|
{
|
||||||
|
//如果文件没有找到,则报错
|
||||||
|
if (!File.Exists(fileToZip))
|
||||||
|
{
|
||||||
|
throw new FileNotFoundException("指定要压缩的文件: " + fileToZip + " 不存在!");
|
||||||
|
}
|
||||||
|
|
||||||
|
using (FileStream ZipFile = File.Create(zipedFile))
|
||||||
|
{
|
||||||
|
using (ZipOutputStream ZipStream = new ZipOutputStream(ZipFile))
|
||||||
|
{
|
||||||
|
using (FileStream StreamToZip = new FileStream(fileToZip, FileMode.Open, FileAccess.Read))
|
||||||
|
{
|
||||||
|
string fileName = fileToZip.Substring(fileToZip.LastIndexOf("\\") + 1);
|
||||||
|
|
||||||
|
ZipEntry ZipEntry = new ZipEntry(fileName);
|
||||||
|
|
||||||
|
ZipStream.PutNextEntry(ZipEntry);
|
||||||
|
|
||||||
|
ZipStream.SetLevel(compressionLevel);
|
||||||
|
|
||||||
|
byte[] buffer = new byte[blockSize];
|
||||||
|
|
||||||
|
int sizeRead = 0;
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
do
|
||||||
|
{
|
||||||
|
sizeRead = StreamToZip.Read(buffer, 0, buffer.Length);
|
||||||
|
ZipStream.Write(buffer, 0, sizeRead);
|
||||||
|
}
|
||||||
|
while (sizeRead > 0);
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
StreamToZip.Close();
|
||||||
|
}
|
||||||
|
|
||||||
|
ZipStream.Finish();
|
||||||
|
ZipStream.Close();
|
||||||
|
}
|
||||||
|
|
||||||
|
ZipFile.Close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 压缩单个文件
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="fileToZip">要进行压缩的文件名</param>
|
||||||
|
/// <param name="zipedFile">压缩后生成的压缩文件名</param>
|
||||||
|
public static void ZipFile(string fileToZip, string zipedFile)
|
||||||
|
{
|
||||||
|
//如果文件没有找到,则报错
|
||||||
|
if (!File.Exists(fileToZip))
|
||||||
|
{
|
||||||
|
throw new FileNotFoundException("指定要压缩的文件: " + fileToZip + " 不存在!");
|
||||||
|
}
|
||||||
|
|
||||||
|
using (FileStream fs = File.OpenRead(fileToZip))
|
||||||
|
{
|
||||||
|
byte[] buffer = new byte[fs.Length];
|
||||||
|
fs.Read(buffer, 0, buffer.Length);
|
||||||
|
fs.Close();
|
||||||
|
|
||||||
|
using (FileStream ZipFile = File.Create(zipedFile))
|
||||||
|
{
|
||||||
|
using (ZipOutputStream ZipStream = new ZipOutputStream(ZipFile))
|
||||||
|
{
|
||||||
|
string fileName = fileToZip.Substring(fileToZip.LastIndexOf("\\") + 1);
|
||||||
|
ZipEntry ZipEntry = new ZipEntry(fileName);
|
||||||
|
ZipStream.PutNextEntry(ZipEntry);
|
||||||
|
ZipStream.SetLevel(5);
|
||||||
|
|
||||||
|
ZipStream.Write(buffer, 0, buffer.Length);
|
||||||
|
ZipStream.Finish();
|
||||||
|
ZipStream.Close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 压缩多个文件到指定路径
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="sourceFileNames">压缩到哪个路径</param>
|
||||||
|
/// <param name="zipFileName">压缩文件名称</param>
|
||||||
|
public static void ZipFile(List<string> sourceFileNames, string zipFileName)
|
||||||
|
{
|
||||||
|
//压缩文件打包
|
||||||
|
using (ZipOutputStream s = new ZipOutputStream(File.Create(zipFileName)))
|
||||||
|
{
|
||||||
|
s.SetLevel(9);
|
||||||
|
byte[] buffer = new byte[4096];
|
||||||
|
foreach (string file in sourceFileNames)
|
||||||
|
{
|
||||||
|
if (Directory.Exists(file))// 先当作目录处理如果存在这个目录就递归Copy该目录下面的文件
|
||||||
|
{
|
||||||
|
string pPath = "";
|
||||||
|
pPath += Path.GetFileName(file);
|
||||||
|
pPath += "\\";
|
||||||
|
ZipSetp(file, s, pPath, sourceFileNames);
|
||||||
|
}
|
||||||
|
else // 否则直接压缩文件
|
||||||
|
{
|
||||||
|
|
||||||
|
ZipEntry entry = new ZipEntry(Path.GetFileName(file));
|
||||||
|
entry.DateTime = DateTime.Now;
|
||||||
|
s.PutNextEntry(entry);
|
||||||
|
using (FileStream fs = File.OpenRead(file))
|
||||||
|
{
|
||||||
|
int sourceBytes;
|
||||||
|
do
|
||||||
|
{
|
||||||
|
sourceBytes = fs.Read(buffer, 0, buffer.Length);
|
||||||
|
s.Write(buffer, 0, sourceBytes);
|
||||||
|
} while (sourceBytes > 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
s.Finish();
|
||||||
|
s.Close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 压缩多层目录
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="strDirectory">待压缩目录</param>
|
||||||
|
/// <param name="zipedFile">压缩后生成的压缩文件名,绝对路径</param>
|
||||||
|
public static void ZipFileDirectory(string strDirectory, string zipedFile)
|
||||||
|
{
|
||||||
|
using (FileStream ZipFile = File.Create(zipedFile))
|
||||||
|
{
|
||||||
|
using (ZipOutputStream s = new ZipOutputStream(ZipFile))
|
||||||
|
{
|
||||||
|
s.SetLevel(9);
|
||||||
|
ZipSetp(strDirectory, s, "");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 压缩多层目录
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="strDirectory">待压缩目录</param>
|
||||||
|
/// <param name="zipedFile">压缩后生成的压缩文件名,绝对路径</param>
|
||||||
|
/// <param name="files">指定要压缩的文件列表(完全路径)</param>
|
||||||
|
public static void ZipFileDirectory(string strDirectory, string zipedFile, List<string> files)
|
||||||
|
{
|
||||||
|
using (FileStream ZipFile = File.Create(zipedFile))
|
||||||
|
{
|
||||||
|
using (ZipOutputStream s = new ZipOutputStream(ZipFile))
|
||||||
|
{
|
||||||
|
s.SetLevel(9);
|
||||||
|
ZipSetp(strDirectory, s, "", files);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 递归遍历目录
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="strDirectory">需遍历的目录</param>
|
||||||
|
/// <param name="s">压缩输出流对象</param>
|
||||||
|
/// <param name="parentPath">The parent path.</param>
|
||||||
|
/// <param name="files">需要压缩的文件</param>
|
||||||
|
private static void ZipSetp(string strDirectory, ZipOutputStream s, string parentPath, List<string> files = null!)
|
||||||
|
{
|
||||||
|
if (strDirectory[strDirectory.Length - 1] != Path.DirectorySeparatorChar)
|
||||||
|
{
|
||||||
|
strDirectory += Path.DirectorySeparatorChar;
|
||||||
|
}
|
||||||
|
|
||||||
|
string[] filenames = Directory.GetFileSystemEntries(strDirectory);
|
||||||
|
|
||||||
|
byte[] buffer = new byte[4096];
|
||||||
|
foreach (string file in filenames)// 遍历所有的文件和目录
|
||||||
|
{
|
||||||
|
if (files != null && !files.Contains(file))
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (Directory.Exists(file))// 先当作目录处理如果存在这个目录就递归Copy该目录下面的文件
|
||||||
|
{
|
||||||
|
string pPath = parentPath;
|
||||||
|
pPath += Path.GetFileName(file);
|
||||||
|
pPath += "\\";
|
||||||
|
ZipSetp(file, s, pPath, files!);
|
||||||
|
}
|
||||||
|
else // 否则直接压缩文件
|
||||||
|
{
|
||||||
|
//打开压缩文件
|
||||||
|
string fileName = parentPath + Path.GetFileName(file);
|
||||||
|
ZipEntry entry = new ZipEntry(fileName);
|
||||||
|
|
||||||
|
entry.DateTime = DateTime.Now;
|
||||||
|
|
||||||
|
s.PutNextEntry(entry);
|
||||||
|
using (FileStream fs = File.OpenRead(file))
|
||||||
|
{
|
||||||
|
int sourceBytes;
|
||||||
|
do
|
||||||
|
{
|
||||||
|
sourceBytes = fs.Read(buffer, 0, buffer.Length);
|
||||||
|
s.Write(buffer, 0, sourceBytes);
|
||||||
|
} while (sourceBytes > 0);
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 解压缩一个 zip 文件。
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="zipedFile">压缩文件</param>
|
||||||
|
/// <param name="strDirectory">解压目录</param>
|
||||||
|
/// <param name="password">zip 文件的密码。</param>
|
||||||
|
/// <param name="overWrite">是否覆盖已存在的文件。</param>
|
||||||
|
public static void UnZip(string zipedFile, string strDirectory, bool overWrite, string password)
|
||||||
|
{
|
||||||
|
|
||||||
|
if (strDirectory == "")
|
||||||
|
strDirectory = Directory.GetCurrentDirectory();
|
||||||
|
if (!strDirectory.EndsWith("\\"))
|
||||||
|
strDirectory = strDirectory + "\\";
|
||||||
|
|
||||||
|
using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipedFile)))
|
||||||
|
{
|
||||||
|
if (password != null)
|
||||||
|
{
|
||||||
|
s.Password = password;
|
||||||
|
}
|
||||||
|
ZipEntry theEntry;
|
||||||
|
|
||||||
|
while ((theEntry = s.GetNextEntry()) != null)
|
||||||
|
{
|
||||||
|
string directoryName = "";
|
||||||
|
string pathToZip = "";
|
||||||
|
pathToZip = theEntry.Name;
|
||||||
|
|
||||||
|
if (pathToZip != "")
|
||||||
|
directoryName = Path.GetDirectoryName(pathToZip) + "\\";
|
||||||
|
|
||||||
|
string fileName = Path.GetFileName(pathToZip);
|
||||||
|
|
||||||
|
Directory.CreateDirectory(strDirectory + directoryName);
|
||||||
|
|
||||||
|
if (fileName != "")
|
||||||
|
{
|
||||||
|
if (File.Exists(strDirectory + directoryName + fileName) && overWrite || !File.Exists(strDirectory + directoryName + fileName))
|
||||||
|
{
|
||||||
|
using (FileStream streamWriter = File.Create(strDirectory + directoryName + fileName))
|
||||||
|
{
|
||||||
|
int size = 2048;
|
||||||
|
byte[] data = new byte[2048];
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
size = s.Read(data, 0, data.Length);
|
||||||
|
|
||||||
|
if (size > 0)
|
||||||
|
streamWriter.Write(data, 0, size);
|
||||||
|
else
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
streamWriter.Close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
s.Close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 解压缩一个 zip 文件。
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="zipedFile">压缩文件</param>
|
||||||
|
/// <param name="strDirectory">解压目录</param>
|
||||||
|
/// <param name="overWrite">是否覆盖已存在的文件。</param>
|
||||||
|
public static void UnZip(string zipedFile, string strDirectory, bool overWrite)
|
||||||
|
{
|
||||||
|
UnZip(zipedFile, strDirectory, overWrite, null!);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 解压缩一个 zip 文件。
|
||||||
|
/// 覆盖已存在的文件。
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="zipedFile">压缩文件</param>
|
||||||
|
/// <param name="strDirectory">解压目录</param>
|
||||||
|
public static void UnZip(string zipedFile, string strDirectory)
|
||||||
|
{
|
||||||
|
UnZip(zipedFile, strDirectory, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取压缩文件中指定类型的文件
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="zipedFile">压缩文件</param>
|
||||||
|
/// <param name="fileExtension">文件类型(.txt|.exe)</param>
|
||||||
|
/// <returns>文件名称列表(包含子目录)</returns>
|
||||||
|
public static List<string> GetFiles(string zipedFile, List<string> fileExtension)
|
||||||
|
{
|
||||||
|
List<string> files = new List<string>();
|
||||||
|
if (!File.Exists(zipedFile))
|
||||||
|
{
|
||||||
|
//return files;
|
||||||
|
throw new FileNotFoundException(zipedFile);
|
||||||
|
}
|
||||||
|
|
||||||
|
using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipedFile)))
|
||||||
|
{
|
||||||
|
ZipEntry theEntry;
|
||||||
|
while ((theEntry = s.GetNextEntry()) != null)
|
||||||
|
{
|
||||||
|
if (theEntry.IsFile)
|
||||||
|
{
|
||||||
|
//Console.WriteLine("Name : {0}", theEntry.Name);
|
||||||
|
if (fileExtension != null)
|
||||||
|
{
|
||||||
|
if (fileExtension.Contains(Path.GetExtension(theEntry.Name)))
|
||||||
|
{
|
||||||
|
files.Add(theEntry.Name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
files.Add(theEntry.Name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
s.Close();
|
||||||
|
}
|
||||||
|
|
||||||
|
return files;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取压缩文件中的所有文件
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="zipedFile">压缩文件</param>
|
||||||
|
/// <returns>文件名称列表(包含子目录)</returns>
|
||||||
|
public static List<string> GetFiles(string zipedFile)
|
||||||
|
{
|
||||||
|
return GetFiles(zipedFile, null!);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
}//Class_end
|
||||||
|
|
||||||
|
}
|
||||||
@@ -8,6 +8,7 @@
|
|||||||
<PackageReference Include="EPPlus" Version="5.8.4" />
|
<PackageReference Include="EPPlus" Version="5.8.4" />
|
||||||
<PackageReference Include="Microsoft.Extensions.Localization.Abstractions" Version="6.0.3" />
|
<PackageReference Include="Microsoft.Extensions.Localization.Abstractions" Version="6.0.3" />
|
||||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
|
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
|
||||||
|
<PackageReference Include="SharpZipLib" Version="1.3.3" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
|||||||
@@ -18,28 +18,33 @@ namespace Yi.Framework.Core
|
|||||||
public delegate T MyAction<T>(CSRedisClient client);
|
public delegate T MyAction<T>(CSRedisClient client);
|
||||||
|
|
||||||
private readonly RedisConnOptions _RedisOptions;
|
private readonly RedisConnOptions _RedisOptions;
|
||||||
|
|
||||||
|
private CSRedisClient Client { get; set; }
|
||||||
|
|
||||||
|
public CSRedisClient _Db { get { return Client; } set { } }
|
||||||
public CacheClientDB(IOptionsMonitor<RedisConnOptions> redisConnOptions)
|
public CacheClientDB(IOptionsMonitor<RedisConnOptions> redisConnOptions)
|
||||||
{
|
{
|
||||||
this._RedisOptions = redisConnOptions.CurrentValue;
|
this._RedisOptions = redisConnOptions.CurrentValue;
|
||||||
|
Client = new CSRedisClient($"{_RedisOptions.Host}:{_RedisOptions.Prot},password={_RedisOptions.Password},defaultDatabase ={ _RedisOptions.DB }");
|
||||||
}
|
}
|
||||||
|
|
||||||
private T TryCatch<T>(MyAction<T> action)
|
private T TryCatch<T>(MyAction<T> action)
|
||||||
{
|
{
|
||||||
var client2 = new CSRedisClient($"{_RedisOptions.Host}:{_RedisOptions.Prot},password={_RedisOptions.Password},defaultDatabase ={ _RedisOptions.DB }");
|
|
||||||
T result;
|
|
||||||
|
T result = default(T);
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
result = action(client2);
|
result = action(Client);
|
||||||
}
|
}
|
||||||
catch (Exception exinfo)
|
catch (Exception exinfo)
|
||||||
{
|
{
|
||||||
object p = null;
|
|
||||||
result = (T)p;
|
|
||||||
Console.WriteLine(exinfo);
|
Console.WriteLine(exinfo);
|
||||||
}
|
}
|
||||||
finally
|
//finally
|
||||||
{
|
//{
|
||||||
client2.Dispose();
|
// Client.Dispose();
|
||||||
}
|
//}
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
@@ -55,6 +60,11 @@ namespace Yi.Framework.Core
|
|||||||
return this.TryCatch((u) => u.Del(key));
|
return this.TryCatch((u) => u.Del(key));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public long HRemove(string key, params string[] par)
|
||||||
|
{
|
||||||
|
return this.TryCatch((u) => u.HDel(key, par));
|
||||||
|
}
|
||||||
|
|
||||||
public T Get<T>(string key)
|
public T Get<T>(string key)
|
||||||
{
|
{
|
||||||
return this.TryCatch<T>((u) => u.Get<T>(key));
|
return this.TryCatch<T>((u) => u.Get<T>(key));
|
||||||
@@ -68,9 +78,36 @@ namespace Yi.Framework.Core
|
|||||||
{
|
{
|
||||||
return this.TryCatch<bool>((u) => u.Set(key, data));
|
return this.TryCatch<bool>((u) => u.Set(key, data));
|
||||||
}
|
}
|
||||||
public bool AddHash<T>(string key,string field, T data)
|
public T QueuePop<T>(string key)
|
||||||
{
|
{
|
||||||
return this.TryCatch<bool>((u)=>u.HSet(key ,field,data));
|
return this.TryCatch<T>((u) => u.RPop<T>(key));
|
||||||
|
}
|
||||||
|
public long QueuePush<T>(string key, T data)
|
||||||
|
{
|
||||||
|
return this.TryCatch<long>((u) => u.LPush<T>(key, data));
|
||||||
|
}
|
||||||
|
public long QueueLen(string key)
|
||||||
|
{
|
||||||
|
return TryCatch((u) => u.LLen(key));
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool HSet<T>(string key, string fieId, T data)
|
||||||
|
{
|
||||||
|
return this.TryCatch<bool>((u) => u.HSet(key, fieId, data));
|
||||||
|
}
|
||||||
|
public bool HSet<T>(string key, string fieId, T data, TimeSpan time)
|
||||||
|
{
|
||||||
|
return this.TryCatch<bool>((u) =>
|
||||||
|
{
|
||||||
|
var res = u.HSet(key, fieId, data);
|
||||||
|
u.Expire(key, time);
|
||||||
|
return res;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public CSRedisClient Db()
|
||||||
|
{
|
||||||
|
return new CSRedisClient($"{_RedisOptions.Host}:{_RedisOptions.Prot},password={_RedisOptions.Password},defaultDatabase ={ _RedisOptions.DB }");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,15 +23,15 @@ namespace Yi.Framework.Core
|
|||||||
}
|
}
|
||||||
public string GetRefreshToken(UserEntity user)
|
public string GetRefreshToken(UserEntity user)
|
||||||
{
|
{
|
||||||
return this.GetToken(_JWTTokenOptions.ReExpiration, user, true);
|
return this.GetToken(_JWTTokenOptions.ReExpiration, user,null, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
public string GetAccessToken(UserEntity user)
|
public string GetAccessToken(UserEntity user,HashSet<MenuEntity> menus)
|
||||||
{
|
{
|
||||||
return this.GetToken(_JWTTokenOptions.Expiration, user);
|
return this.GetToken(_JWTTokenOptions.Expiration, user, menus);
|
||||||
}
|
}
|
||||||
|
|
||||||
private string GetToken(int minutes, UserEntity user, bool isRefresh = false)
|
private string GetToken(int minutes, UserEntity user, HashSet<MenuEntity> menus,bool isRefresh = false)
|
||||||
{
|
{
|
||||||
List<Claim> claims = new List<Claim>();
|
List<Claim> claims = new List<Claim>();
|
||||||
claims.Add(new Claim(JwtRegisteredClaimNames.Nbf, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"));
|
claims.Add(new Claim(JwtRegisteredClaimNames.Nbf, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"));
|
||||||
@@ -39,8 +39,11 @@ namespace Yi.Framework.Core
|
|||||||
claims.Add(new Claim(JwtRegisteredClaimNames.Sid, user.Id.ToString()));
|
claims.Add(new Claim(JwtRegisteredClaimNames.Sid, user.Id.ToString()));
|
||||||
|
|
||||||
//-----------------------------以下从user的权限表中添加权限-----------------------例如:
|
//-----------------------------以下从user的权限表中添加权限-----------------------例如:
|
||||||
claims.Add(new Claim("permission", "userentity:get:list"));
|
|
||||||
claims.Add(new Claim("permission", "userentity:get:one"));
|
foreach (var m in menus)
|
||||||
|
{
|
||||||
|
claims.Add(new Claim("permission", m.PermissionCode.ToString()));
|
||||||
|
}
|
||||||
|
|
||||||
if (isRefresh)
|
if (isRefresh)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -18,6 +18,8 @@ namespace Yi.Framework.Core
|
|||||||
private IScheduler _scheduler;
|
private IScheduler _scheduler;
|
||||||
private ILogger<QuartzInvoker> _logger;
|
private ILogger<QuartzInvoker> _logger;
|
||||||
private IJobFactory _jobFactory;
|
private IJobFactory _jobFactory;
|
||||||
|
|
||||||
|
private const string JobDllName = "Yi.Framework.Job";
|
||||||
public QuartzInvoker(ISchedulerFactory schedulerFactory, ILogger<QuartzInvoker> logger, IJobFactory jobFactory)
|
public QuartzInvoker(ISchedulerFactory schedulerFactory, ILogger<QuartzInvoker> logger, IJobFactory jobFactory)
|
||||||
{
|
{
|
||||||
_schedulerFactory = schedulerFactory;
|
_schedulerFactory = schedulerFactory;
|
||||||
@@ -29,27 +31,28 @@ namespace Yi.Framework.Core
|
|||||||
/// 开始任务
|
/// 开始任务
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="cron"></param>
|
/// <param name="cron"></param>
|
||||||
/// <param name="jobKey"></param>
|
|
||||||
/// <param name="jobClass"></param>
|
/// <param name="jobClass"></param>
|
||||||
|
/// <param name="jobName"></param>
|
||||||
|
/// <param name="jobGroup"></param>
|
||||||
/// <param name="second"></param>
|
/// <param name="second"></param>
|
||||||
/// <param name="data"></param>
|
/// <param name="data"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public async Task start(string cron, JobKey jobKey, string dllName,string jobClass, long second = 0, IDictionary<string, object> data = null)
|
public async Task StartAsync(string cron, string jobClass, string jobName = "", string jobGroup = "default", long startAtSecondTime = 0, IDictionary<string, object> data = null)
|
||||||
{
|
{
|
||||||
|
jobName = jobName == "" ? jobClass : jobName;
|
||||||
if (data == null)
|
if (data == null)
|
||||||
{
|
{
|
||||||
data = new Dictionary<string, object>();
|
data = new Dictionary<string, object>();
|
||||||
}
|
}
|
||||||
|
JobKey jobKey = new JobKey(jobName, jobGroup);
|
||||||
var myClass = AssemblyHelper.GetClass(dllName, jobClass).FirstOrDefault();
|
var myClass = AssemblyHelper.GetClass(JobDllName, jobClass).FirstOrDefault();
|
||||||
|
|
||||||
_scheduler = await _schedulerFactory.GetScheduler();
|
_scheduler = await _schedulerFactory.GetScheduler();
|
||||||
_scheduler.JobFactory = _jobFactory;
|
_scheduler.JobFactory = _jobFactory;
|
||||||
//开启调度器
|
|
||||||
await _scheduler.Start();
|
|
||||||
//创建一个触发器
|
//创建一个触发器
|
||||||
var trigger = TriggerBuilder.Create()
|
var trigger = TriggerBuilder.Create()
|
||||||
.StartAt(DateTimeOffset.Now.AddSeconds(second))
|
.StartAt(DateTimeOffset.Now.AddSeconds(startAtSecondTime))
|
||||||
.WithCronSchedule(cron)
|
.WithCronSchedule(cron)
|
||||||
.Build();
|
.Build();
|
||||||
//创建任务
|
//创建任务
|
||||||
@@ -57,18 +60,78 @@ namespace Yi.Framework.Core
|
|||||||
.UsingJobData(new JobDataMap(data))
|
.UsingJobData(new JobDataMap(data))
|
||||||
.WithIdentity(jobKey.Name, jobKey.Group)
|
.WithIdentity(jobKey.Name, jobKey.Group)
|
||||||
.Build();
|
.Build();
|
||||||
|
|
||||||
|
//await _scheduler.AddJob(jobDetail,false);
|
||||||
|
|
||||||
|
//await _scheduler.ScheduleJob(trigger);
|
||||||
//将触发器和任务器绑定到调度器中
|
//将触发器和任务器绑定到调度器中
|
||||||
await _scheduler.ScheduleJob(jobDetail, trigger);
|
await _scheduler.ScheduleJob(jobDetail, trigger);
|
||||||
|
|
||||||
|
//开启调度器
|
||||||
|
await _scheduler.Start();
|
||||||
|
|
||||||
_logger.LogWarning($"开始任务:{jobKey.Name},组别:{jobKey.Group}");
|
_logger.LogWarning($"开始任务:{jobKey.Name},组别:{jobKey.Group}");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 开始任务
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="cron"></param>
|
||||||
|
/// <param name="jobClass"></param>
|
||||||
|
/// <param name="jobName"></param>
|
||||||
|
/// <param name="jobGroup"></param>
|
||||||
|
/// <param name="second"></param>
|
||||||
|
/// <param name="data"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public async Task StartAsync(int milliSecondTime, string jobClass, string jobName = "", string jobGroup = "default", long startAtSecondTime = 0, IDictionary<string, object> data = null)
|
||||||
|
{
|
||||||
|
|
||||||
|
jobName = jobName == "" ? jobClass : jobName;
|
||||||
|
|
||||||
|
if (data == null)
|
||||||
|
{
|
||||||
|
data = new Dictionary<string, object>();
|
||||||
|
}
|
||||||
|
JobKey jobKey = new JobKey(jobName, jobGroup);
|
||||||
|
var myClass = AssemblyHelper.GetClass(JobDllName, jobClass).FirstOrDefault();
|
||||||
|
|
||||||
|
_scheduler = await _schedulerFactory.GetScheduler();
|
||||||
|
_scheduler.JobFactory = _jobFactory;
|
||||||
|
|
||||||
|
//创建一个触发器
|
||||||
|
var trigger = TriggerBuilder.Create()
|
||||||
|
.StartAt(DateTimeOffset.Now.AddSeconds(startAtSecondTime))
|
||||||
|
.WithSimpleSchedule(option =>
|
||||||
|
{
|
||||||
|
option.WithInterval(TimeSpan.FromMilliseconds(milliSecondTime)).RepeatForever();
|
||||||
|
})
|
||||||
|
|
||||||
|
.Build();
|
||||||
|
//创建任务
|
||||||
|
var jobDetail = JobBuilder.Create(myClass)
|
||||||
|
.UsingJobData(new JobDataMap(data))
|
||||||
|
.WithIdentity(jobKey.Name, jobKey.Group)
|
||||||
|
.Build();
|
||||||
|
|
||||||
|
//await _scheduler.AddJob(jobDetail,false);
|
||||||
|
|
||||||
|
//await _scheduler.ScheduleJob(trigger);
|
||||||
|
//将触发器和任务器绑定到调度器中
|
||||||
|
await _scheduler.ScheduleJob(jobDetail, trigger);
|
||||||
|
|
||||||
|
//开启调度器
|
||||||
|
await _scheduler.Start();
|
||||||
|
|
||||||
|
_logger.LogWarning($"开始任务:{jobKey.Name},组别:{jobKey.Group}");
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 暂停任务
|
/// 暂停任务
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="jobKey"></param>
|
/// <param name="jobKey"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public async Task Stop(JobKey jobKey)
|
public async Task StopAsync(JobKey jobKey)
|
||||||
{
|
{
|
||||||
var _scheduler = await _schedulerFactory.GetScheduler();
|
var _scheduler = await _schedulerFactory.GetScheduler();
|
||||||
//LogUtil.Debug($"暂停任务{jobKey.Group},{jobKey.Name}");
|
//LogUtil.Debug($"暂停任务{jobKey.Group},{jobKey.Name}");
|
||||||
@@ -77,7 +140,7 @@ namespace Yi.Framework.Core
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public async Task Delete(JobKey jobKey)
|
public async Task DeleteAsync(JobKey jobKey)
|
||||||
{
|
{
|
||||||
var _scheduler = await _schedulerFactory.GetScheduler();
|
var _scheduler = await _schedulerFactory.GetScheduler();
|
||||||
//LogUtil.Debug($"暂停任务{jobKey.Group},{jobKey.Name}");
|
//LogUtil.Debug($"暂停任务{jobKey.Group},{jobKey.Name}");
|
||||||
@@ -85,7 +148,7 @@ namespace Yi.Framework.Core
|
|||||||
_logger.LogWarning($"删除任务:{jobKey.Name},组别:{jobKey.Group}");
|
_logger.LogWarning($"删除任务:{jobKey.Name},组别:{jobKey.Group}");
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task Resume(JobKey jobKey)
|
public async Task ResumeAsync(JobKey jobKey)
|
||||||
{
|
{
|
||||||
var _scheduler = await _schedulerFactory.GetScheduler();
|
var _scheduler = await _schedulerFactory.GetScheduler();
|
||||||
//LogUtil.Debug($"恢复任务{jobKey.Group},{jobKey.Name}");
|
//LogUtil.Debug($"恢复任务{jobKey.Group},{jobKey.Name}");
|
||||||
@@ -98,9 +161,9 @@ namespace Yi.Framework.Core
|
|||||||
/// 得到可运行的job列表
|
/// 得到可运行的job列表
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public List<string> getJobClassList()
|
public List<string> GetJobClassList()
|
||||||
{
|
{
|
||||||
var myClassList = AssemblyHelper.GetClass("Yi.Framework.Job");
|
var myClassList = AssemblyHelper.GetClass("ETX.Job");
|
||||||
List<string> data = new List<string>();
|
List<string> data = new List<string>();
|
||||||
myClassList.ForEach(k => data.Add(k.Name));
|
myClassList.ForEach(k => data.Add(k.Name));
|
||||||
return data;
|
return data;
|
||||||
@@ -126,9 +189,9 @@ namespace Yi.Framework.Core
|
|||||||
foreach (ITrigger trigger in triggers)
|
foreach (ITrigger trigger in triggers)
|
||||||
{
|
{
|
||||||
///下一次的执行时间
|
///下一次的执行时间
|
||||||
var utcTime =trigger.GetNextFireTimeUtc();
|
var utcTime = trigger.GetNextFireTimeUtc();
|
||||||
string str = utcTime.ToString();
|
string str = utcTime.ToString();
|
||||||
//TimeZone.CurrentTimeZone.ToLocalTime(Convert.ToDateTime(str));
|
//TimeZone.CurrentTimeZone.ToLocalTime(Convert.ToDateTime(str));
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -142,7 +205,7 @@ namespace Yi.Framework.Core
|
|||||||
|
|
||||||
|
|
||||||
public class JobKeyModel
|
public class JobKeyModel
|
||||||
{
|
{
|
||||||
public JobKey jobKey { get; set; }
|
public JobKey jobKey { get; set; }
|
||||||
public DateTime? nextTime { get; set; }
|
public DateTime? nextTime { get; set; }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -246,7 +246,7 @@ namespace Yi.Framework.Core
|
|||||||
autoAck: false,//不ACK
|
autoAck: false,//不ACK
|
||||||
consumer: consumer);
|
consumer: consumer);
|
||||||
Console.WriteLine($" Register Consumer To {rabbitMQConsumerMode.ExchangeName}-{rabbitMQConsumerMode.QueueName}");
|
Console.WriteLine($" Register Consumer To {rabbitMQConsumerMode.ExchangeName}-{rabbitMQConsumerMode.QueueName}");
|
||||||
Console.ReadLine();
|
//Console.ReadLine();
|
||||||
Console.WriteLine($" After Register Consumer To {rabbitMQConsumerMode.ExchangeName}-{rabbitMQConsumerMode.QueueName}");
|
Console.WriteLine($" After Register Consumer To {rabbitMQConsumerMode.ExchangeName}-{rabbitMQConsumerMode.QueueName}");
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -18,8 +18,6 @@
|
|||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<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" />
|
<ProjectReference Include="..\Yi.Framework.Task\Yi.Framework.Job.csproj" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
|||||||
@@ -10,7 +10,6 @@
|
|||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ProjectReference Include="..\Yi.Framework.DTOModel\Yi.Framework.DTOModel.csproj" />
|
<ProjectReference Include="..\Yi.Framework.DTOModel\Yi.Framework.DTOModel.csproj" />
|
||||||
<ProjectReference Include="..\Yi.Framework.Model\Yi.Framework.Model.csproj" />
|
|
||||||
<ProjectReference Include="..\Yi.Framework.Repository\Yi.Framework.Repository.csproj" />
|
<ProjectReference Include="..\Yi.Framework.Repository\Yi.Framework.Repository.csproj" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ namespace Yi.Framework.Model.Models
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
///
|
///
|
||||||
///</summary>
|
///</summary>
|
||||||
[SugarColumn(ColumnName= "PermissionCode")]
|
[SugarColumn(ColumnName="PermissionCode" )]
|
||||||
public string PermissionCode { get; set; }
|
public string PermissionCode { get; set; }
|
||||||
/// <summary>
|
/// <summary>
|
||||||
///
|
///
|
||||||
@@ -69,5 +69,15 @@ namespace Yi.Framework.Model.Models
|
|||||||
///</summary>
|
///</summary>
|
||||||
[SugarColumn(ColumnName="TenantId" )]
|
[SugarColumn(ColumnName="TenantId" )]
|
||||||
public long? TenantId { get; set; }
|
public long? TenantId { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
///
|
||||||
|
///</summary>
|
||||||
|
[SugarColumn(ColumnName="MenuIcon" )]
|
||||||
|
public string MenuIcon { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
///
|
||||||
|
///</summary>
|
||||||
|
[SugarColumn(ColumnName="Router" )]
|
||||||
|
public string Router { get; set; }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -54,5 +54,10 @@ namespace Yi.Framework.Model.Models
|
|||||||
///</summary>
|
///</summary>
|
||||||
[SugarColumn(ColumnName="ModifyUser" )]
|
[SugarColumn(ColumnName="ModifyUser" )]
|
||||||
public long? ModifyUser { get; set; }
|
public long? ModifyUser { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
///
|
||||||
|
///</summary>
|
||||||
|
[SugarColumn(ColumnName="RoleCode" )]
|
||||||
|
public string RoleCode { get; set; }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ namespace Yi.Framework.Model.Query
|
|||||||
public List<QueryParameter> Parameters { get; set; } = new List<QueryParameter>();
|
public List<QueryParameter> Parameters { get; set; } = new List<QueryParameter>();
|
||||||
public List<string> OrderBys { get; set; } = new List<string>();
|
public List<string> OrderBys { get; set; } = new List<string>();
|
||||||
|
|
||||||
|
public bool IsAsc { get; set; } = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
public class QueryCondition
|
public class QueryCondition
|
||||||
@@ -21,5 +22,7 @@ namespace Yi.Framework.Model.Query
|
|||||||
public List<QueryParameter> Parameters { get; set; } = new List<QueryParameter>();
|
public List<QueryParameter> Parameters { get; set; } = new List<QueryParameter>();
|
||||||
public List<string> OrderBys { get; set; } = new List<string>();
|
public List<string> OrderBys { get; set; } = new List<string>();
|
||||||
|
|
||||||
|
public bool IsAsc { get; set; } = false;
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
using Newtonsoft.Json.Converters;
|
using Newtonsoft.Json;
|
||||||
|
using Newtonsoft.Json.Converters;
|
||||||
using SqlSugar;
|
using SqlSugar;
|
||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
using System.Text.Json.Serialization;
|
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
namespace Yi.Framework.Model.Query
|
namespace Yi.Framework.Model.Query
|
||||||
|
|||||||
@@ -6,7 +6,7 @@
|
|||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="NEST" Version="7.16.0" />
|
<PackageReference Include="NEST" Version="7.16.0" />
|
||||||
<PackageReference Include="SqlSugarCore" Version="5.0.7.5" />
|
<PackageReference Include="SqlSugarCore" Version="5.0.7.8" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
|||||||
@@ -21,8 +21,11 @@ namespace Yi.Framework.Repository
|
|||||||
public Task<List<T>> GetListAsync(QueryCondition pars);
|
public Task<List<T>> GetListAsync(QueryCondition pars);
|
||||||
public Task<bool> DeleteByLogicAsync(List<long> ids);
|
public Task<bool> DeleteByLogicAsync(List<long> ids);
|
||||||
public Task<bool> UpdateIgnoreNullAsync(T entity);
|
public Task<bool> UpdateIgnoreNullAsync(T entity);
|
||||||
public Task<List<S>> UseSqlAsync<S>(string sql);
|
public Task<List<S>> UseSqlAsync<S>(string sql, object parameters = null);
|
||||||
public Task<bool> UseSqlAsync(string sql);
|
public Task<bool> UseSqlAsync(string sql, object parameters = null);
|
||||||
ISugarQueryable<T> QueryConditionHandler(QueryCondition pars);
|
ISugarQueryable<T> QueryConditionHandler(QueryCondition pars);
|
||||||
|
Task<bool> UpdateSuperSaveAsync(T data, Expression<Func<T, object>> columns);
|
||||||
|
Task<List<T>> GetListAsync(Expression<Func<T, bool>> where, Expression<Func<T, object>> order, OrderByType orderByType = OrderByType.Desc);
|
||||||
|
Task<T> GetFirstAsync(Expression<Func<T, bool>> where, Expression<Func<T, object>> order, OrderByType orderByType = OrderByType.Desc);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -42,24 +42,21 @@ namespace Yi.Framework.Repository
|
|||||||
/// <typeparam name="S"></typeparam>
|
/// <typeparam name="S"></typeparam>
|
||||||
/// <param name="sql"></param>
|
/// <param name="sql"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public async Task<List<S>> UseSqlAsync<S>(string sql)
|
public async Task<List<S>> UseSqlAsync<S>(string sql, object parameters = null)
|
||||||
{
|
{
|
||||||
return await _Db.Ado.SqlQueryAsync<S>(sql);
|
return await _Db.Ado.SqlQueryAsync<S>(sql, parameters);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 执行增删改sql返回状态
|
/// 执行增删改sql返回状态
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="sql"></param>
|
/// <param name="sql"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public async Task<bool> UseSqlAsync(string sql)
|
public async Task<bool> UseSqlAsync(string sql, object parameters)
|
||||||
{
|
{
|
||||||
return await _Db.Ado.ExecuteCommandAsync(sql)>0;
|
return await _Db.Ado.ExecuteCommandAsync(sql, parameters) >0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 添加返回实体
|
/// 添加返回实体
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -147,12 +144,68 @@ namespace Yi.Framework.Repository
|
|||||||
{
|
{
|
||||||
foreach (var item in pars.OrderBys)
|
foreach (var item in pars.OrderBys)
|
||||||
{
|
{
|
||||||
query.OrderBy(item.ToSqlFilter());
|
if (pars.IsAsc)
|
||||||
|
{
|
||||||
|
query.OrderBy(item.ToSqlFilter() + " asc");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
query.OrderBy(item.ToSqlFilter() + " desc");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return query.Where(sugarParamters);
|
return query.Where(sugarParamters);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 更新高级保存,验证重复
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="list"></param>
|
||||||
|
/// <param name="columns"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public async Task<bool> UpdateSuperSaveAsync(T data, Expression<Func<T, object>> columns)
|
||||||
|
{
|
||||||
|
var x = _Db.Storageable(data)
|
||||||
|
.SplitError(it => it.Any())
|
||||||
|
.SplitUpdate(it => true)
|
||||||
|
.WhereColumns(columns)//这里用name作为数据库查找条件
|
||||||
|
.ToStorage();
|
||||||
|
return await x.AsInsertable.ExecuteCommandAsync() > 0;//插入可插入部分
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 添加高级保存,验证重复
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="list"></param>
|
||||||
|
/// <param name="columns"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public async Task<bool> InsertSuperSaveAsync(T data, Expression<Func<T, object>> columns)
|
||||||
|
{
|
||||||
|
var x = _Db.Storageable(data)
|
||||||
|
.SplitError(it => it.Any())
|
||||||
|
.SplitInsert(it => true)
|
||||||
|
.WhereColumns(columns)//这里用name作为数据库查找条件
|
||||||
|
.ToStorage();
|
||||||
|
return await x.AsInsertable.ExecuteCommandAsync() > 0;//插入可插入部分
|
||||||
|
}
|
||||||
|
/// <summary>
|
||||||
|
/// 方法重载,多条件获取第一个值
|
||||||
|
/// </summary>
|
||||||
|
/// <returns></returns>
|
||||||
|
public async Task<T> GetFirstAsync(Expression<Func<T, bool>> where, Expression<Func<T, object>> order, OrderByType orderByType = OrderByType.Desc)
|
||||||
|
{
|
||||||
|
return await _Db.Queryable<T>().Where(where).OrderBy(order, orderByType).FirstAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 方法重载,多条件获取范围
|
||||||
|
/// </summary>
|
||||||
|
/// <returns></returns>
|
||||||
|
public async Task<List<T>> GetListAsync(Expression<Func<T, bool>> where, Expression<Func<T, object>> order, OrderByType orderByType = OrderByType.Desc)
|
||||||
|
{
|
||||||
|
return await _Db.Queryable<T>().Where(where).OrderBy(order, orderByType).ToListAsync();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -11,7 +11,6 @@
|
|||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ProjectReference Include="..\Yi.Framework.Common\Yi.Framework.Common.csproj" />
|
|
||||||
<ProjectReference Include="..\Yi.Framework.Model\Yi.Framework.Model.csproj" />
|
<ProjectReference Include="..\Yi.Framework.Model\Yi.Framework.Model.csproj" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
using SqlSugar;
|
using SqlSugar;
|
||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using Yi.Framework.Common.Helper;
|
using Yi.Framework.Common.Helper;
|
||||||
@@ -112,7 +113,7 @@ namespace Yi.Framework.Service
|
|||||||
//首先获取到该用户全部信息,导航到角色、菜单,(菜单需要去重,完全交给Set来处理即可)
|
//首先获取到该用户全部信息,导航到角色、菜单,(菜单需要去重,完全交给Set来处理即可)
|
||||||
|
|
||||||
//得到用户
|
//得到用户
|
||||||
var user = await _repository._Db.Queryable<UserEntity>().Includes(u => u.Roles, r => r.Menus).InSingleAsync(userId);
|
var user = await _repository._Db.Queryable<UserEntity>().Includes(u => u.Roles.Where(r=>r.IsDeleted==false).ToList(), r => r.Menus.Where(m=>m.IsDeleted==false).ToList()).InSingleAsync(userId);
|
||||||
|
|
||||||
//得到角色集合
|
//得到角色集合
|
||||||
var roleList = user.Roles;
|
var roleList = user.Roles;
|
||||||
|
|||||||
@@ -9,11 +9,7 @@
|
|||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ProjectReference Include="..\Yi.Framework.Core\Yi.Framework.Core.csproj" />
|
|
||||||
<ProjectReference Include="..\Yi.Framework.DTOModel\Yi.Framework.DTOModel.csproj" />
|
|
||||||
<ProjectReference Include="..\Yi.Framework.Interface\Yi.Framework.Interface.csproj" />
|
<ProjectReference Include="..\Yi.Framework.Interface\Yi.Framework.Interface.csproj" />
|
||||||
<ProjectReference Include="..\Yi.Framework.Model\Yi.Framework.Model.csproj" />
|
|
||||||
<ProjectReference Include="..\Yi.Framework.Repository\Yi.Framework.Repository.csproj" />
|
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
|||||||
@@ -9,7 +9,6 @@
|
|||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ProjectReference Include="..\Yi.Framework.Common\Yi.Framework.Common.csproj" />
|
|
||||||
<ProjectReference Include="..\Yi.Framework.Model\Yi.Framework.Model.csproj" />
|
<ProjectReference Include="..\Yi.Framework.Model\Yi.Framework.Model.csproj" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,66 @@
|
|||||||
|
using System;
|
||||||
|
namespace Yi.Framework.WeChatPay.Core
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// IConfig
|
||||||
|
/// </summary>
|
||||||
|
public interface IPayConfig
|
||||||
|
{
|
||||||
|
|
||||||
|
//=======【基本信息设置】=====================================
|
||||||
|
/* 微信公众号信息配置
|
||||||
|
* APPID:绑定支付的APPID(必须配置)
|
||||||
|
* MCHID:商户号(必须配置)
|
||||||
|
* KEY:商户支付密钥,参考开户邮件设置(必须配置),请妥善保管,避免密钥泄露
|
||||||
|
* APPSECRET:公众帐号secert(仅JSAPI支付的时候需要配置),请妥善保管,避免密钥泄露
|
||||||
|
*/
|
||||||
|
|
||||||
|
string GetAppID();
|
||||||
|
string GetMchID();
|
||||||
|
string GetKey();
|
||||||
|
string GetAppSecret();
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
//=======【证书路径设置】=====================================
|
||||||
|
/* 证书路径,注意应该填写绝对路径(仅退款、撤销订单时需要)
|
||||||
|
* 1.证书文件不能放在web服务器虚拟目录,应放在有访问权限控制的目录中,防止被他人下载;
|
||||||
|
* 2.建议将证书文件名改为复杂且不容易猜测的文件
|
||||||
|
* 3.商户服务器要做好病毒和木马防护工作,不被非法侵入者窃取证书文件。
|
||||||
|
*/
|
||||||
|
string GetSSlCertPath();
|
||||||
|
string GetSSlCertPassword();
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
//=======【支付结果通知url】=====================================
|
||||||
|
/* 支付结果通知回调url,用于商户接收支付结果
|
||||||
|
*/
|
||||||
|
string GetNotifyUrl();
|
||||||
|
|
||||||
|
//=======【商户系统后台机器IP】=====================================
|
||||||
|
/* 此参数可手动配置也可在程序中自动获取
|
||||||
|
*/
|
||||||
|
string GetIp();
|
||||||
|
|
||||||
|
|
||||||
|
//=======【代理服务器设置】===================================
|
||||||
|
/* 默认IP和端口号分别为0.0.0.0和0,此时不开启代理(如有需要才设置)
|
||||||
|
*/
|
||||||
|
string GetProxyUrl();
|
||||||
|
|
||||||
|
|
||||||
|
//=======【上报信息配置】===================================
|
||||||
|
/* 测速上报等级,0.关闭上报; 1.仅错误时上报; 2.全量上报
|
||||||
|
*/
|
||||||
|
int GetReportLevel();
|
||||||
|
|
||||||
|
|
||||||
|
//=======【日志级别】===================================
|
||||||
|
/* 日志等级,0.不输出日志;1.只输出错误信息; 2.输出错误和正常信息; 3.输出错误信息、正常信息和调试信息
|
||||||
|
*/
|
||||||
|
int GetLogLevel();
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
using Newtonsoft.Json;
|
||||||
|
using System;
|
||||||
|
using System.IO;
|
||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
|
using Yi.Framework.WeChatPay.Options;
|
||||||
|
|
||||||
|
namespace Yi.Framework.WeChatPay.Core
|
||||||
|
{
|
||||||
|
public class PayConfig : IPayConfig
|
||||||
|
{
|
||||||
|
public static PayConfig Current = null;
|
||||||
|
|
||||||
|
public PayConfig(PayOptions payOptions)
|
||||||
|
{
|
||||||
|
Current = this;
|
||||||
|
_BasicConfig = payOptions;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static PayOptions _BasicConfig = null;
|
||||||
|
|
||||||
|
|
||||||
|
//=======【基本信息设置】=====================================
|
||||||
|
/* 微信公众号信息配置
|
||||||
|
* APPID:绑定支付的APPID(必须配置)
|
||||||
|
* MCHID:商户号(必须配置)
|
||||||
|
* KEY:商户支付密钥,参考开户邮件设置(必须配置),请妥善保管,避免密钥泄露
|
||||||
|
* APPSECRET:公众帐号secert(仅JSAPI支付的时候需要配置),请妥善保管,避免密钥泄露
|
||||||
|
*/
|
||||||
|
|
||||||
|
public string GetAppID()
|
||||||
|
{
|
||||||
|
return _BasicConfig.AppID;
|
||||||
|
}
|
||||||
|
public string GetMchID()
|
||||||
|
{
|
||||||
|
return _BasicConfig.MchID;
|
||||||
|
}
|
||||||
|
public string GetKey()
|
||||||
|
{
|
||||||
|
return _BasicConfig.Key;
|
||||||
|
}
|
||||||
|
public string GetAppSecret()
|
||||||
|
{
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
//=======【证书路径设置】=====================================
|
||||||
|
/* 证书路径,注意应该填写绝对路径(仅退款、撤销订单时需要)
|
||||||
|
* 1.证书文件不能放在web服务器虚拟目录,应放在有访问权限控制的目录中,防止被他人下载;
|
||||||
|
* 2.建议将证书文件名改为复杂且不容易猜测的文件
|
||||||
|
* 3.商户服务器要做好病毒和木马防护工作,不被非法侵入者窃取证书文件。
|
||||||
|
*/
|
||||||
|
public string GetSSlCertPath()
|
||||||
|
{
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
public string GetSSlCertPassword()
|
||||||
|
{
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
//=======【支付结果通知url】=====================================
|
||||||
|
/* 支付结果通知回调url,用于商户接收支付结果
|
||||||
|
*/
|
||||||
|
public string GetNotifyUrl()
|
||||||
|
{
|
||||||
|
return _BasicConfig.NotifyUrl;
|
||||||
|
}
|
||||||
|
|
||||||
|
//=======【商户系统后台机器IP】=====================================
|
||||||
|
/* 此参数可手动配置也可在程序中自动获取
|
||||||
|
*/
|
||||||
|
public string GetIp()
|
||||||
|
{
|
||||||
|
return "0.0.0.0";
|
||||||
|
}
|
||||||
|
|
||||||
|
//=======【代理服务器设置】===================================
|
||||||
|
/* 默认IP和端口号分别为0.0.0.0和0,此时不开启代理(如有需要才设置)
|
||||||
|
*/
|
||||||
|
public string GetProxyUrl()
|
||||||
|
{
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
//=======【上报信息配置】===================================
|
||||||
|
/* 测速上报等级,0.关闭上报; 1.仅错误时上报; 2.全量上报
|
||||||
|
*/
|
||||||
|
public int GetReportLevel()
|
||||||
|
{
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
//=======【日志级别】===================================
|
||||||
|
/* 日志等级,0.不输出日志;1.只输出错误信息; 2.输出错误和正常信息; 3.输出错误信息、正常信息和调试信息
|
||||||
|
*/
|
||||||
|
public int GetLogLevel()
|
||||||
|
{
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
138
Yi.Framework.Net6/Yi.Framework.WeChatPay/Core/Helper/PayApi.cs
Normal file
138
Yi.Framework.Net6/Yi.Framework.WeChatPay/Core/Helper/PayApi.cs
Normal file
@@ -0,0 +1,138 @@
|
|||||||
|
using FizzWare.NBuilder;
|
||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using Yi.Framework.WeChatPay.Exceptions;
|
||||||
|
|
||||||
|
namespace Yi.Framework.WeChatPay.Core
|
||||||
|
{
|
||||||
|
public class PayApi
|
||||||
|
{
|
||||||
|
private readonly IPayConfig _IPayConfig = null;
|
||||||
|
private readonly PayHttpService _PayHttpService = null;
|
||||||
|
public PayApi(IPayConfig payConfig, PayHttpService payHttpService)
|
||||||
|
{
|
||||||
|
this._IPayConfig = payConfig;
|
||||||
|
this._PayHttpService = payHttpService;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* 统一下单
|
||||||
|
* @param WxPaydata inputObj 提交给统一下单API的参数
|
||||||
|
* @param int timeOut 超时时间
|
||||||
|
* @throws WxPayException
|
||||||
|
* @return 成功时返回,其他抛异常
|
||||||
|
*/
|
||||||
|
public PayData UnifiedOrder(PayData inputObj, int timeOut = 6)
|
||||||
|
{
|
||||||
|
string url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
|
||||||
|
//检测必填参数
|
||||||
|
if (!inputObj.IsSet("out_trade_no"))
|
||||||
|
{
|
||||||
|
throw new PayException("缺少统一支付接口必填参数out_trade_no!");
|
||||||
|
}
|
||||||
|
else if (!inputObj.IsSet("body"))
|
||||||
|
{
|
||||||
|
throw new PayException("缺少统一支付接口必填参数body!");
|
||||||
|
}
|
||||||
|
else if (!inputObj.IsSet("total_fee"))
|
||||||
|
{
|
||||||
|
throw new PayException("缺少统一支付接口必填参数total_fee!");
|
||||||
|
}
|
||||||
|
else if (!inputObj.IsSet("trade_type"))
|
||||||
|
{
|
||||||
|
throw new PayException("缺少统一支付接口必填参数trade_type!");
|
||||||
|
}
|
||||||
|
|
||||||
|
//关联参数
|
||||||
|
if (inputObj.GetValue("trade_type").ToString() == "JSAPI" && !inputObj.IsSet("openid"))
|
||||||
|
{
|
||||||
|
throw new PayException("统一支付接口中,缺少必填参数openid!trade_type为JSAPI时,openid为必填参数!");
|
||||||
|
}
|
||||||
|
if (inputObj.GetValue("trade_type").ToString() == "NATIVE" && !inputObj.IsSet("product_id"))
|
||||||
|
{
|
||||||
|
throw new PayException("统一支付接口中,缺少必填参数product_id!trade_type为JSAPI时,product_id为必填参数!");
|
||||||
|
}
|
||||||
|
|
||||||
|
//异步通知url未设置,则使用配置文件中的url
|
||||||
|
/*if (!inputObj.IsSet("notify_url"))
|
||||||
|
{
|
||||||
|
inputObj.SetValue("notify_url", this._IWxPayConfig().GetNotifyUrl());//异步通知url
|
||||||
|
}*/
|
||||||
|
|
||||||
|
inputObj.SetValue("appid", this._IPayConfig.GetAppID());//公众账号ID
|
||||||
|
inputObj.SetValue("mch_id", this._IPayConfig.GetMchID());//商户号
|
||||||
|
inputObj.SetValue("spbill_create_ip", this._IPayConfig.GetIp());//终端ip
|
||||||
|
inputObj.SetValue("nonce_str", GenerateNonceStr());//随机字符串
|
||||||
|
inputObj.SetValue("sign_type", PayData.SIGN_TYPE_HMAC_SHA256);//签名类型
|
||||||
|
|
||||||
|
//签名
|
||||||
|
inputObj.SetValue("sign", inputObj.MakeSign());
|
||||||
|
string xml = inputObj.ToXml();
|
||||||
|
// 发起http请求
|
||||||
|
string response = this._PayHttpService.Post(xml, url, false, timeOut);
|
||||||
|
PayData result = new PayData();
|
||||||
|
result.FromXml(response);
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* 查询订单
|
||||||
|
* @param WxPayData inputObj 提交给查询订单API的参数
|
||||||
|
* @param int timeOut 超时时间
|
||||||
|
* @throws WxPayException
|
||||||
|
* @return 成功时返回订单查询结果,其他抛异常
|
||||||
|
*/
|
||||||
|
public PayData OrderQuery(PayData inputObj, HttpContext httpContext, int timeOut = 6)
|
||||||
|
{
|
||||||
|
string url = "https://api.mch.weixin.qq.com/pay/orderquery";
|
||||||
|
//检测必填参数
|
||||||
|
if (!inputObj.IsSet("out_trade_no") && !inputObj.IsSet("transaction_id"))
|
||||||
|
{
|
||||||
|
throw new PayException("订单查询接口中,out_trade_no、transaction_id至少填一个!");
|
||||||
|
}
|
||||||
|
|
||||||
|
inputObj.SetValue("appid", this._IPayConfig.GetAppID());//公众账号ID
|
||||||
|
inputObj.SetValue("mch_id", this._IPayConfig.GetMchID());//商户号
|
||||||
|
inputObj.SetValue("nonce_str", GenerateNonceStr());//随机字符串
|
||||||
|
inputObj.SetValue("sign_type", PayData.SIGN_TYPE_HMAC_SHA256);//签名类型
|
||||||
|
inputObj.SetValue("sign", inputObj.MakeSign());//签名
|
||||||
|
string xml = inputObj.ToXml();
|
||||||
|
//Log.Debug("WxPayApi", "OrderQuery request : " + xml);
|
||||||
|
string response = this._PayHttpService.Post(xml, url, false, timeOut);//调用HTTP通信接口提交数据
|
||||||
|
//Log.Debug("WxPayApi", "OrderQuery response : " + response);
|
||||||
|
|
||||||
|
//将xml格式的数据转化为对象以返回
|
||||||
|
PayData result = new PayData();
|
||||||
|
result.FromXml(response);
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 生成时间戳,标准北京时间,时区为东八区,自1970年1月1日 0点0分0秒以来的秒数
|
||||||
|
* @return 时间戳
|
||||||
|
*/
|
||||||
|
public static string GenerateTimeStamp()
|
||||||
|
{
|
||||||
|
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
|
||||||
|
return Convert.ToInt64(ts.TotalSeconds).ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 生成随机串,随机串包含字母或数字
|
||||||
|
* @return 随机串
|
||||||
|
*/
|
||||||
|
public static string GenerateNonceStr()
|
||||||
|
{
|
||||||
|
RandomGenerator randomGenerator = new RandomGenerator();
|
||||||
|
return randomGenerator.Int().ToString();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
322
Yi.Framework.Net6/Yi.Framework.WeChatPay/Core/Helper/PayData.cs
Normal file
322
Yi.Framework.Net6/Yi.Framework.WeChatPay/Core/Helper/PayData.cs
Normal file
@@ -0,0 +1,322 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Web;
|
||||||
|
using System.Xml;
|
||||||
|
using System.Security.Cryptography;
|
||||||
|
using System.Text;
|
||||||
|
using System.Linq;
|
||||||
|
using Newtonsoft.Json;
|
||||||
|
using Yi.Framework.WeChatPay.Core;
|
||||||
|
|
||||||
|
namespace Yi.Framework.WeChatPay.Core
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 微信支付协议接口数据类,所有的API接口通信都依赖这个数据结构,
|
||||||
|
/// 在调用接口之前先填充各个字段的值,然后进行接口通信,
|
||||||
|
/// 这样设计的好处是可扩展性强,用户可随意对协议进行更改而不用重新设计数据结构,
|
||||||
|
/// 还可以随意组合出不同的协议数据包,不用为每个协议设计一个数据包结构
|
||||||
|
/// </summary>
|
||||||
|
public class PayData
|
||||||
|
{
|
||||||
|
public const string SIGN_TYPE_MD5 = "MD5";
|
||||||
|
public const string SIGN_TYPE_HMAC_SHA256 = "HMAC-SHA256";
|
||||||
|
|
||||||
|
|
||||||
|
//采用排序的Dictionary的好处是方便对数据包进行签名,不用再签名之前再做一次排序
|
||||||
|
private SortedDictionary<string, object> m_values = new SortedDictionary<string, object>();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 设置某个字段的值
|
||||||
|
* @param key 字段名
|
||||||
|
* @param value 字段值
|
||||||
|
*/
|
||||||
|
public void SetValue(string key, object value)
|
||||||
|
{
|
||||||
|
m_values[key] = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据字段名获取某个字段的值
|
||||||
|
* @param key 字段名
|
||||||
|
* @return key对应的字段值
|
||||||
|
*/
|
||||||
|
public object GetValue(string key)
|
||||||
|
{
|
||||||
|
object o = null;
|
||||||
|
m_values.TryGetValue(key, out o);
|
||||||
|
return o;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 判断某个字段是否已设置
|
||||||
|
* @param key 字段名
|
||||||
|
* @return 若字段key已被设置,则返回true,否则返回false
|
||||||
|
*/
|
||||||
|
public bool IsSet(string key)
|
||||||
|
{
|
||||||
|
object o = null;
|
||||||
|
m_values.TryGetValue(key, out o);
|
||||||
|
if (null != o && !o.Equals(""))
|
||||||
|
return true;
|
||||||
|
else
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @将Dictionary转成xml
|
||||||
|
* @return 经转换得到的xml串
|
||||||
|
* @throws WxPayException
|
||||||
|
**/
|
||||||
|
public string ToXml()
|
||||||
|
{
|
||||||
|
//数据为空时不能转化为xml格式
|
||||||
|
if (0 == m_values.Count)
|
||||||
|
{
|
||||||
|
throw new Exception("WxPayData数据为空!");
|
||||||
|
}
|
||||||
|
|
||||||
|
string xml = "<xml>";
|
||||||
|
foreach (KeyValuePair<string, object> pair in m_values)
|
||||||
|
{
|
||||||
|
//字段值不能为null,会影响后续流程
|
||||||
|
if (pair.Value == null)
|
||||||
|
{
|
||||||
|
throw new Exception("WxPayData内部含有值为null的字段!");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (pair.Value.GetType() == typeof(int))
|
||||||
|
{
|
||||||
|
xml += "<" + pair.Key + ">" + pair.Value + "</" + pair.Key + ">";
|
||||||
|
}
|
||||||
|
else if (pair.Value.GetType() == typeof(string))
|
||||||
|
{
|
||||||
|
xml += "<" + pair.Key + ">" + "<![CDATA[" + pair.Value + "]]></" + pair.Key + ">";
|
||||||
|
}
|
||||||
|
else//除了string和int类型不能含有其他数据类型
|
||||||
|
{
|
||||||
|
throw new Exception("WxPayData字段数据类型错误!");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
xml += "</xml>";
|
||||||
|
return xml;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @将xml转为WxPayData对象并返回对象内部的数据
|
||||||
|
* @param string 待转换的xml串
|
||||||
|
* @return 经转换得到的Dictionary
|
||||||
|
* @throws WxPayException
|
||||||
|
*/
|
||||||
|
public SortedDictionary<string, object> FromXml(string xml)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(xml))
|
||||||
|
{
|
||||||
|
throw new Exception("将空的xml串转换为WxPayData不合法!");
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
SafeXmlDocument xmlDoc = new SafeXmlDocument();
|
||||||
|
xmlDoc.LoadXml(xml);
|
||||||
|
XmlNode xmlNode = xmlDoc.FirstChild;//获取到根节点<xml>
|
||||||
|
XmlNodeList nodes = xmlNode.ChildNodes;
|
||||||
|
foreach (XmlNode xn in nodes)
|
||||||
|
{
|
||||||
|
XmlElement xe = (XmlElement)xn;
|
||||||
|
m_values[xe.Name] = xe.InnerText;//获取xml的键值对到WxPayData内部的数据中
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
//2015-06-29 错误是没有签名
|
||||||
|
if (m_values["return_code"].ToString() != "SUCCESS")
|
||||||
|
{
|
||||||
|
return m_values;
|
||||||
|
}
|
||||||
|
//验证签名,不通过会抛异常
|
||||||
|
CheckSign();
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
throw new Exception(ex.Message);
|
||||||
|
}
|
||||||
|
|
||||||
|
return m_values;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @Dictionary格式转化成url参数格式
|
||||||
|
* @ return url格式串, 该串不包含sign字段值
|
||||||
|
*/
|
||||||
|
public string ToUrl()
|
||||||
|
{
|
||||||
|
string buff = "";
|
||||||
|
foreach (KeyValuePair<string, object> pair in m_values)
|
||||||
|
{
|
||||||
|
if (pair.Value == null)
|
||||||
|
{
|
||||||
|
throw new Exception("WxPayData内部含有值为null的字段!");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (pair.Key != "sign" && pair.Value.ToString() != "")
|
||||||
|
{
|
||||||
|
buff += pair.Key + "=" + pair.Value + "&";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
buff = buff.Trim('&');
|
||||||
|
return buff;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @Dictionary格式化成Json
|
||||||
|
* @return json串数据
|
||||||
|
*/
|
||||||
|
public string ToJson()
|
||||||
|
{
|
||||||
|
string jsonStr = JsonConvert.SerializeObject(m_values);
|
||||||
|
return jsonStr;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @values格式化成能在Web页面上显示的结果(因为web页面上不能直接输出xml格式的字符串)
|
||||||
|
*/
|
||||||
|
public string ToPrintStr()
|
||||||
|
{
|
||||||
|
string str = "";
|
||||||
|
foreach (KeyValuePair<string, object> pair in m_values)
|
||||||
|
{
|
||||||
|
if (pair.Value == null)
|
||||||
|
{
|
||||||
|
throw new Exception("WxPayData内部含有值为null的字段!");
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
str += string.Format("{0}={1}\n", pair.Key, pair.Value.ToString());
|
||||||
|
}
|
||||||
|
str = HttpUtility.HtmlEncode(str);
|
||||||
|
return str;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @生成签名,详见签名生成算法
|
||||||
|
* @return 签名, sign字段不参加签名
|
||||||
|
*/
|
||||||
|
public string MakeSign(string signType)
|
||||||
|
{
|
||||||
|
//转url格式
|
||||||
|
string str = ToUrl();
|
||||||
|
//在string后加入API KEY
|
||||||
|
string apiKey = PayConfig.Current.GetKey();
|
||||||
|
str += "&key=" + apiKey;
|
||||||
|
if (signType == SIGN_TYPE_MD5)
|
||||||
|
{
|
||||||
|
var md5 = MD5.Create();
|
||||||
|
var bs = md5.ComputeHash(Encoding.UTF8.GetBytes(str));
|
||||||
|
var sb = new StringBuilder();
|
||||||
|
foreach (byte b in bs)
|
||||||
|
{
|
||||||
|
sb.Append(b.ToString("x2"));
|
||||||
|
}
|
||||||
|
//所有字符转为大写
|
||||||
|
return sb.ToString().ToUpper();
|
||||||
|
}
|
||||||
|
else if (signType == SIGN_TYPE_HMAC_SHA256)
|
||||||
|
{
|
||||||
|
return CalcHMACSHA256Hash(str, apiKey);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
throw new Exception("sign_type 不合法");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @生成签名,详见签名生成算法
|
||||||
|
* @return 签名, sign字段不参加签名 SHA256
|
||||||
|
*/
|
||||||
|
public string MakeSign()
|
||||||
|
{
|
||||||
|
return MakeSign(SIGN_TYPE_HMAC_SHA256);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* 检测签名是否正确
|
||||||
|
* 正确返回true,错误抛异常
|
||||||
|
*/
|
||||||
|
public bool CheckSign(string signType)
|
||||||
|
{
|
||||||
|
//如果没有设置签名,则跳过检测
|
||||||
|
if (!IsSet("sign"))
|
||||||
|
{
|
||||||
|
throw new Exception("WxPayData签名存在但不合法!");
|
||||||
|
}
|
||||||
|
//如果设置了签名但是签名为空,则抛异常
|
||||||
|
else if (GetValue("sign") == null || GetValue("sign").ToString() == "")
|
||||||
|
{
|
||||||
|
throw new Exception("WxPayData签名存在但不合法!");
|
||||||
|
}
|
||||||
|
|
||||||
|
//获取接收到的签名
|
||||||
|
string return_sign = GetValue("sign").ToString();
|
||||||
|
|
||||||
|
//在本地计算新的签名
|
||||||
|
string cal_sign = MakeSign(signType);
|
||||||
|
|
||||||
|
if (cal_sign == return_sign)
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Exception("WxPayData签名验证错误!");
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* 检测签名是否正确
|
||||||
|
* 正确返回true,错误抛异常
|
||||||
|
*/
|
||||||
|
public bool CheckSign()
|
||||||
|
{
|
||||||
|
return CheckSign(SIGN_TYPE_HMAC_SHA256);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @获取Dictionary
|
||||||
|
*/
|
||||||
|
public SortedDictionary<string, object> GetValues()
|
||||||
|
{
|
||||||
|
return m_values;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
private string CalcHMACSHA256Hash(string plaintext, string salt)
|
||||||
|
{
|
||||||
|
string result = "";
|
||||||
|
var enc = Encoding.Default;
|
||||||
|
byte[]
|
||||||
|
baText2BeHashed = enc.GetBytes(plaintext),
|
||||||
|
baSalt = enc.GetBytes(salt);
|
||||||
|
HMACSHA256 hasher = new HMACSHA256(baSalt);
|
||||||
|
byte[] baHashedText = hasher.ComputeHash(baText2BeHashed);
|
||||||
|
result = string.Join("", baHashedText.ToList().Select(b => b.ToString("x2")).ToArray());
|
||||||
|
return result.ToUpper();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
private class SafeXmlDocument : XmlDocument
|
||||||
|
{
|
||||||
|
public SafeXmlDocument()
|
||||||
|
{
|
||||||
|
this.XmlResolver = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,178 @@
|
|||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
|
using Newtonsoft.Json;
|
||||||
|
using Newtonsoft.Json.Linq;
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Net;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using Yi.Framework.WeChatPay.Options;
|
||||||
|
|
||||||
|
namespace Yi.Framework.WeChatPay.Core
|
||||||
|
{
|
||||||
|
public class PayHelper
|
||||||
|
{
|
||||||
|
public static readonly string KEY_PAY_PREFIX = "order:pay:url:";
|
||||||
|
private readonly IPayConfig _IPayConfig = null;
|
||||||
|
private readonly PayApi _PayApi = null;
|
||||||
|
|
||||||
|
private HttpContext _httpContext;
|
||||||
|
public PayHelper(IPayConfig PayConfig, PayApi PayApi, IHttpContextAccessor httpContextAccessor)
|
||||||
|
{
|
||||||
|
this._IPayConfig = PayConfig;
|
||||||
|
this._PayApi = PayApi;
|
||||||
|
this._httpContext = httpContextAccessor.HttpContext;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 创建支付连接
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="orderId"></param>
|
||||||
|
/// <param name="description"></param>
|
||||||
|
/// <param name="totalPay"></param>
|
||||||
|
/// <param name="httpContext"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public string CreatePayUrl(long orderId, string description, long totalPay)
|
||||||
|
{
|
||||||
|
// 定义返回的支付连接
|
||||||
|
string url;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
// 构建支付需要的参数对象
|
||||||
|
PayData data = new PayData();
|
||||||
|
//描述
|
||||||
|
data.SetValue("body", description);
|
||||||
|
//订单号
|
||||||
|
data.SetValue("out_trade_no", orderId.ToString());
|
||||||
|
data.SetValue("product_id", orderId.ToString());
|
||||||
|
//货币(默认就是人民币)
|
||||||
|
data.SetValue("fee_type", "CNY");
|
||||||
|
//TODO 总金额 (模拟1分钱, 线上环境换成真实价格)
|
||||||
|
data.SetValue("total_fee", /*totalPay.ToString()*/ 1); // 单位是分
|
||||||
|
//调用微信支付的终端ip
|
||||||
|
data.SetValue("spbill_create_ip", "0.0.0.0");
|
||||||
|
//回调地址
|
||||||
|
data.SetValue("notify_url", this._IPayConfig.GetNotifyUrl());
|
||||||
|
//交易类型为扫码支付
|
||||||
|
data.SetValue("trade_type", "NATIVE");
|
||||||
|
|
||||||
|
PayData result = this._PayApi.UnifiedOrder(data);//调用统一下单接口
|
||||||
|
url = result.GetValue("code_url").ToString();//获得统一下单接口返回的二维码链接
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
throw new Exception("生成支付链接连接失败", e);
|
||||||
|
}
|
||||||
|
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// (调用微信API)根据订单ID查询订单信息,全部信息
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="transaction_id"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public PayData QueryOrderById(long orderId)
|
||||||
|
{
|
||||||
|
PayData req = new PayData();
|
||||||
|
req.SetValue("out_trade_no", orderId.ToString());
|
||||||
|
PayData res = this._PayApi.OrderQuery(req, _httpContext);
|
||||||
|
return res;// 返回查询数据
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
public static PayOptions GetPayOptions(string path)
|
||||||
|
{
|
||||||
|
string config = File.ReadAllText(path);
|
||||||
|
var option = JsonConvert.DeserializeObject<PayOptions>(config);
|
||||||
|
Console.WriteLine($"configPath={path} AppID={option.AppID}");
|
||||||
|
return option;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 生成二维码方法
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="text">输入的字符串</param>
|
||||||
|
/// <param name="width">二维码宽度</param>
|
||||||
|
/// <param name="height">二维码高度</param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public static string QRcode(string text, int width = 360, int height = 360)
|
||||||
|
{
|
||||||
|
|
||||||
|
//这里要感谢一下http://old.wwei.cn/
|
||||||
|
Dictionary<string, string> dic = new()
|
||||||
|
{
|
||||||
|
{ "qrid", "0" },
|
||||||
|
{ "data[type]", "index" },
|
||||||
|
{ "data[text]", text },
|
||||||
|
{ "moban_id", "0" },
|
||||||
|
{ "size", "300" },
|
||||||
|
{ "level", "M" },
|
||||||
|
{ "moban_type", "qrcpu" },
|
||||||
|
{ "style_setting[protype]", "1" },
|
||||||
|
{ "style_setting[ptcolor]", "#000000" },
|
||||||
|
{ "style_setting[inptcolor]", "#000000" },
|
||||||
|
{ "style_setting[fcolor]", "#000000" },
|
||||||
|
{ "style_setting[bcolor]", "#ffffff" },
|
||||||
|
{ "style_setting[mbtype_hb]", "0" },
|
||||||
|
{ "style_setting[logo_id]", "" },
|
||||||
|
{ "style_setting[logo_width]", "46" },
|
||||||
|
{ "style_setting[logo_height]", "46" },
|
||||||
|
{ "style_setting[logo_border]", "0" }
|
||||||
|
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
StringBuilder builder = new StringBuilder();
|
||||||
|
int i = 0;
|
||||||
|
if (dic.Count > 0)
|
||||||
|
{
|
||||||
|
foreach (var item in dic)
|
||||||
|
{
|
||||||
|
if (i > 0)
|
||||||
|
builder.Append("&");
|
||||||
|
builder.AppendFormat("{0}={1}", item.Key, item.Value);
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
string postDataStr = builder.ToString();
|
||||||
|
|
||||||
|
|
||||||
|
#pragma warning disable SYSLIB0014 // 类型或成员已过时
|
||||||
|
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://old.wwei.cn/qrcode-wwei_create.html");
|
||||||
|
#pragma warning restore SYSLIB0014 // 类型或成员已过时
|
||||||
|
|
||||||
|
request.Method = "POST";
|
||||||
|
request.ContentType = "application/x-www-form-urlencoded";
|
||||||
|
request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr);
|
||||||
|
request.Headers.Add("Host", "old.wwei.cn");
|
||||||
|
request.Headers.Add("User-Agent", "PostmanRuntime/6.66.6");
|
||||||
|
request.Headers.Add("Origin", "http://old.wwei.cn");
|
||||||
|
request.Headers.Add("Referer", "http://old.wwei.cn/");
|
||||||
|
|
||||||
|
Stream myRequestStream = request.GetRequestStream();
|
||||||
|
StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("utf-8"));
|
||||||
|
myStreamWriter.Write(postDataStr);
|
||||||
|
myStreamWriter.Close();
|
||||||
|
|
||||||
|
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();
|
||||||
|
|
||||||
|
var json = Newtonsoft.Json.JsonConvert.DeserializeObject<JObject>(retString);
|
||||||
|
var data = json["data"].ToString();
|
||||||
|
|
||||||
|
return data;
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,196 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Web;
|
||||||
|
using System.Net;
|
||||||
|
using System.IO;
|
||||||
|
using System.Text;
|
||||||
|
using System.Net.Security;
|
||||||
|
using System.Security.Authentication;
|
||||||
|
using System.Security.Cryptography.X509Certificates;
|
||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
|
using Yi.Framework.WeChatPay.Exceptions;
|
||||||
|
|
||||||
|
namespace Yi.Framework.WeChatPay.Core
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// http连接基础类,负责底层的http通信
|
||||||
|
/// </summary>
|
||||||
|
public class PayHttpService
|
||||||
|
{
|
||||||
|
private readonly IPayConfig _IPayConfig = null;
|
||||||
|
private readonly HttpContext _httpContext = null;
|
||||||
|
public PayHttpService(IPayConfig PayConfig, IHttpContextAccessor httpContextAccessor)
|
||||||
|
{
|
||||||
|
this._IPayConfig = PayConfig;
|
||||||
|
this._httpContext = httpContextAccessor.HttpContext;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
|
||||||
|
{
|
||||||
|
//直接确认,否则打不开
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public string Post(string xml, string url, bool isUseCert, int timeout)
|
||||||
|
{
|
||||||
|
System.GC.Collect();//垃圾回收,回收没有正常关闭的http连接
|
||||||
|
|
||||||
|
string result = "";//返回结果
|
||||||
|
|
||||||
|
|
||||||
|
HttpWebRequest request = null;
|
||||||
|
HttpWebResponse response = null;
|
||||||
|
Stream reqStream = null;
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
//设置最大连接数
|
||||||
|
ServicePointManager.DefaultConnectionLimit = 200;
|
||||||
|
//设置https验证方式
|
||||||
|
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
ServicePointManager.ServerCertificateValidationCallback =
|
||||||
|
new RemoteCertificateValidationCallback(CheckValidationResult);
|
||||||
|
}
|
||||||
|
|
||||||
|
/***************************************************************
|
||||||
|
* 下面设置HttpWebRequest的相关属性
|
||||||
|
* ************************************************************/
|
||||||
|
#pragma warning disable SYSLIB0014 // 类型或成员已过时
|
||||||
|
request = (HttpWebRequest)WebRequest.Create(url);
|
||||||
|
#pragma warning restore SYSLIB0014 // 类型或成员已过时
|
||||||
|
request.UserAgent = string.Format("WXPaySDK/{3} ({0}) .net/{1} {2}", Environment.OSVersion, Environment.Version, this._IPayConfig.GetMchID(), typeof(PayHttpService).Assembly.GetName().Version);
|
||||||
|
request.Method = "POST";
|
||||||
|
request.Timeout = timeout * 1000;
|
||||||
|
|
||||||
|
//设置POST的数据类型和长度
|
||||||
|
request.ContentType = "text/xml";
|
||||||
|
byte[] data = Encoding.UTF8.GetBytes(xml);
|
||||||
|
request.ContentLength = data.Length;
|
||||||
|
|
||||||
|
|
||||||
|
if (isUseCert)//是否使用证书--没用证书
|
||||||
|
{
|
||||||
|
string path = _httpContext.Request.Path;
|
||||||
|
X509Certificate2 cert = new X509Certificate2(path + this._IPayConfig.GetSSlCertPath(), this._IPayConfig.GetSSlCertPassword());
|
||||||
|
request.ClientCertificates.Add(cert);
|
||||||
|
}
|
||||||
|
|
||||||
|
//往服务器写入数据
|
||||||
|
reqStream = request.GetRequestStream();
|
||||||
|
reqStream.Write(data, 0, data.Length);
|
||||||
|
reqStream.Close();
|
||||||
|
|
||||||
|
//获取服务端返回
|
||||||
|
response = (HttpWebResponse)request.GetResponse();
|
||||||
|
|
||||||
|
//获取服务端返回数据
|
||||||
|
StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
|
||||||
|
result = sr.ReadToEnd().Trim();
|
||||||
|
sr.Close();
|
||||||
|
}
|
||||||
|
catch (System.Threading.ThreadAbortException)
|
||||||
|
{
|
||||||
|
#pragma warning disable SYSLIB0006 // 类型或成员已过时
|
||||||
|
Thread.ResetAbort();
|
||||||
|
#pragma warning restore SYSLIB0006 // 类型或成员已过时
|
||||||
|
}
|
||||||
|
catch (WebException e)
|
||||||
|
{
|
||||||
|
if (e.Status == WebExceptionStatus.ProtocolError)
|
||||||
|
{
|
||||||
|
throw new PayException(e.ToString());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
throw new PayException(e.ToString());
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
//关闭连接和流
|
||||||
|
if (response != null)
|
||||||
|
{
|
||||||
|
response.Close();
|
||||||
|
}
|
||||||
|
if (request != null)
|
||||||
|
{
|
||||||
|
request.Abort();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 处理http GET请求,返回数据
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="url">请求的url地址</param>
|
||||||
|
/// <returns>http GET成功后返回的数据,失败抛WebException异常</returns>
|
||||||
|
public string Get(string url)
|
||||||
|
{
|
||||||
|
System.GC.Collect();
|
||||||
|
string result = "";
|
||||||
|
|
||||||
|
HttpWebRequest request = null;
|
||||||
|
HttpWebResponse response = null;
|
||||||
|
|
||||||
|
//请求url以获取数据
|
||||||
|
try
|
||||||
|
{
|
||||||
|
//设置最大连接数
|
||||||
|
ServicePointManager.DefaultConnectionLimit = 200;
|
||||||
|
//设置https验证方式
|
||||||
|
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
ServicePointManager.ServerCertificateValidationCallback =
|
||||||
|
new RemoteCertificateValidationCallback(CheckValidationResult);
|
||||||
|
}
|
||||||
|
|
||||||
|
/***************************************************************
|
||||||
|
* 下面设置HttpWebRequest的相关属性
|
||||||
|
* ************************************************************/
|
||||||
|
#pragma warning disable SYSLIB0014 // 类型或成员已过时
|
||||||
|
request = (HttpWebRequest)WebRequest.Create(url);
|
||||||
|
#pragma warning restore SYSLIB0014 // 类型或成员已过时
|
||||||
|
request.UserAgent = string.Format("WXPaySDK/{3} ({0}) .net/{1} {2}", Environment.OSVersion, Environment.Version, this._IPayConfig.GetMchID(), typeof(PayHttpService).Assembly.GetName().Version);
|
||||||
|
request.Method = "GET";
|
||||||
|
|
||||||
|
//获取服务器返回
|
||||||
|
response = (HttpWebResponse)request.GetResponse();
|
||||||
|
|
||||||
|
//获取HTTP返回数据
|
||||||
|
StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
|
||||||
|
result = sr.ReadToEnd().Trim();
|
||||||
|
sr.Close();
|
||||||
|
}
|
||||||
|
catch (System.Threading.ThreadAbortException)
|
||||||
|
{
|
||||||
|
#pragma warning disable SYSLIB0006 // 类型或成员已过时
|
||||||
|
Thread.ResetAbort();
|
||||||
|
#pragma warning restore SYSLIB0006 // 类型或成员已过时
|
||||||
|
}
|
||||||
|
catch (WebException e)
|
||||||
|
{
|
||||||
|
throw new PayException(e.ToString());
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
throw new PayException(e.ToString());
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
//关闭连接和流
|
||||||
|
if (response != null)
|
||||||
|
{
|
||||||
|
response.Close();
|
||||||
|
}
|
||||||
|
if (request != null)
|
||||||
|
{
|
||||||
|
request.Abort();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
29
Yi.Framework.Net6/Yi.Framework.WeChatPay/Core/IPayInvoker.cs
Normal file
29
Yi.Framework.Net6/Yi.Framework.WeChatPay/Core/IPayInvoker.cs
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace Yi.Framework.WeChatPay.Core
|
||||||
|
{
|
||||||
|
public interface IPayInvoker
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 获取WX支付链接的方法
|
||||||
|
/// 然后发布定时同步状态任务
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="orderId">订单ID</param>
|
||||||
|
/// <param name="user">用户信息</param>
|
||||||
|
/// <param name="httpContext">请求上下文</param>
|
||||||
|
/// <returns>返回生成的支持链接</returns>
|
||||||
|
string GenerateUrl(long orderId, long totalPay);
|
||||||
|
/// <summary>
|
||||||
|
/// 处理微信支付回调
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="httpContext"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
PayData HandleNotify();
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.IO;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using Yi.Framework.WeChatPay.Exceptions;
|
||||||
|
|
||||||
|
namespace Yi.Framework.WeChatPay.Core
|
||||||
|
{
|
||||||
|
public abstract class AbstractNotify
|
||||||
|
{
|
||||||
|
protected HttpContext _httpContext;
|
||||||
|
|
||||||
|
public AbstractNotify(IHttpContextAccessor httpContextAccessor)
|
||||||
|
{
|
||||||
|
this._httpContext = httpContextAccessor.HttpContext;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 从请求对象中获取信息
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request"></param>
|
||||||
|
/// <param name="encoding"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
private async Task<string> GetRawBodyStringAsync(HttpRequest request, Encoding encoding = null)
|
||||||
|
{
|
||||||
|
if (encoding is null)
|
||||||
|
{
|
||||||
|
encoding = Encoding.UTF8;
|
||||||
|
}
|
||||||
|
var stream = new MemoryStream();
|
||||||
|
await request.Body.CopyToAsync(stream);
|
||||||
|
stream.Seek(0, 0);
|
||||||
|
using (var reader = new StreamReader(stream, encoding))
|
||||||
|
{
|
||||||
|
var result = await reader.ReadToEndAsync();
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 接收从微信支付后台发送过来的数据并验证签名
|
||||||
|
/// </summary>
|
||||||
|
/// <returns>微信支付后台返回的数据</returns>
|
||||||
|
public PayData GetNotifyData()
|
||||||
|
{
|
||||||
|
//接收从微信后台POST过来的数据
|
||||||
|
string content = GetRawBodyStringAsync(_httpContext.Request).Result;
|
||||||
|
Console.WriteLine(this.GetType().ToString(), "Receive data from WeChat : " + content);
|
||||||
|
|
||||||
|
//转换数据格式并验证签名
|
||||||
|
PayData data = new PayData();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
data.FromXml(content);
|
||||||
|
}
|
||||||
|
catch (PayException ex)
|
||||||
|
{
|
||||||
|
throw new Exception("验签失败", ex);
|
||||||
|
}
|
||||||
|
|
||||||
|
Console.WriteLine(this.GetType().ToString(), "Check sign success");
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
//派生类需要重写这个方法,进行不同的回调处理
|
||||||
|
public abstract PayData ProcessNotify();
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
|
||||||
|
namespace Yi.Framework.WeChatPay.Core
|
||||||
|
{
|
||||||
|
public class ResultNotify : AbstractNotify
|
||||||
|
{
|
||||||
|
private readonly PayApi _PayApi;
|
||||||
|
private readonly ILogger<ResultNotify> _logger;
|
||||||
|
public ResultNotify(PayApi PayApi,ILogger<ResultNotify> logger, IHttpContextAccessor httpContextAccessor) :base(httpContextAccessor)
|
||||||
|
{
|
||||||
|
this._PayApi = PayApi;
|
||||||
|
this._logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 处理支付回调
|
||||||
|
/// </summary>
|
||||||
|
/// <returns></returns>
|
||||||
|
public override PayData ProcessNotify()
|
||||||
|
{
|
||||||
|
PayData notifyData = GetNotifyData();
|
||||||
|
//解析数据
|
||||||
|
string totalFee = notifyData.GetValue("total_fee").ToString(); //订单金额
|
||||||
|
string outTradeNo = notifyData.GetValue("out_trade_no").ToString(); //订单编号
|
||||||
|
string transactionId = notifyData.GetValue("transaction_id").ToString(); //商户订单号
|
||||||
|
string bankType = notifyData.GetValue("bank_type").ToString(); //银行类型
|
||||||
|
|
||||||
|
_logger.LogInformation($"======支付回调参数:{totalFee}=={outTradeNo}=={transactionId}=={bankType}");
|
||||||
|
if (totalFee.Equals("") || outTradeNo.Equals("") || transactionId.Equals("") || bankType.Equals(""))
|
||||||
|
{
|
||||||
|
PayData res = new();
|
||||||
|
res.SetValue("return_code", "FAIL");
|
||||||
|
res.SetValue("return_msg", "支付回调返回数据不正确");
|
||||||
|
_logger.LogInformation("支付错误结果 : " + res.ToXml());
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
//检查支付结果中transaction_id是否存在--流水号
|
||||||
|
if (!notifyData.IsSet("transaction_id"))
|
||||||
|
{
|
||||||
|
//若transaction_id不存在,则立即返回结果给微信支付后台
|
||||||
|
PayData res = new();
|
||||||
|
res.SetValue("return_code", "FAIL");
|
||||||
|
res.SetValue("return_msg", "支付结果中微信订单号不存在");
|
||||||
|
_logger.LogInformation("支付错误结果 : " + res.ToXml());
|
||||||
|
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
//查询订单,判断订单真实性
|
||||||
|
if (!QueryOrder(transactionId))
|
||||||
|
{
|
||||||
|
//若订单查询失败,则立即返回结果给微信支付后台
|
||||||
|
PayData res = new();
|
||||||
|
res.SetValue("return_code", "FAIL");
|
||||||
|
res.SetValue("return_msg", "订单查询失败");
|
||||||
|
_logger.LogInformation("订单查询失败 : " + res.ToXml());
|
||||||
|
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
//查询订单成功
|
||||||
|
else
|
||||||
|
{
|
||||||
|
// 打印结果 (仅打印)
|
||||||
|
PayData res = new PayData();
|
||||||
|
res.SetValue("return_code", "SUCCESS");
|
||||||
|
res.SetValue("return_msg", "OK");
|
||||||
|
res.SetValue("transaction_id", transactionId);
|
||||||
|
_logger.LogInformation("订单查成功: " + res.ToXml());
|
||||||
|
|
||||||
|
// 设置返回响应结果
|
||||||
|
notifyData.SetValue("return_code", "SUCCESS");
|
||||||
|
notifyData.SetValue("return_msg", "OK");
|
||||||
|
|
||||||
|
return notifyData;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 根据流水号查询订单信息
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="transaction_id"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
private bool QueryOrder(string transaction_id)
|
||||||
|
{
|
||||||
|
PayData req = new PayData();
|
||||||
|
req.SetValue("transaction_id", transaction_id);
|
||||||
|
PayData res = this._PayApi.OrderQuery(req, _httpContext);
|
||||||
|
if (res.GetValue("return_code").ToString() == "SUCCESS" &&
|
||||||
|
res.GetValue("result_code").ToString() == "SUCCESS")
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
55
Yi.Framework.Net6/Yi.Framework.WeChatPay/Core/PayInvoker.cs
Normal file
55
Yi.Framework.Net6/Yi.Framework.WeChatPay/Core/PayInvoker.cs
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using Yi.Framework.WeChatPay.Options;
|
||||||
|
|
||||||
|
namespace Yi.Framework.WeChatPay.Core
|
||||||
|
{
|
||||||
|
public class PayInvoker:IPayInvoker
|
||||||
|
{
|
||||||
|
private readonly PayHelper _payHelper;
|
||||||
|
private readonly ILogger<PayInvoker> _logger;
|
||||||
|
private readonly AbstractNotify _notify;
|
||||||
|
|
||||||
|
public PayInvoker(PayHelper payHelper, ILogger<PayInvoker> logger, AbstractNotify notify)
|
||||||
|
{
|
||||||
|
this._payHelper = payHelper;
|
||||||
|
this._logger = logger;
|
||||||
|
this._notify = notify;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取WX支付链接的方法
|
||||||
|
/// 然后发布定时同步状态任务
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="orderId">订单ID</param>
|
||||||
|
/// <param name="user">用户信息</param>
|
||||||
|
/// <param name="httpContext">请求上下文</param>
|
||||||
|
/// <returns>返回生成的支持链接</returns>
|
||||||
|
public string GenerateUrl(long orderId, long totalPay)
|
||||||
|
{
|
||||||
|
string payUrl = null;
|
||||||
|
_logger.LogInformation("准备生成支付链接.....");
|
||||||
|
payUrl = _payHelper.CreatePayUrl(orderId, "微信支付链接", totalPay);
|
||||||
|
_logger.LogInformation("生成支付链接为:{payUrl}", payUrl);
|
||||||
|
return payUrl;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 处理微信支付回调
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="httpContext"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public PayData HandleNotify()
|
||||||
|
{
|
||||||
|
PayData wxPayData = this._notify.ProcessNotify();
|
||||||
|
|
||||||
|
return wxPayData;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
using System;
|
||||||
|
using System.Runtime.Serialization;
|
||||||
|
|
||||||
|
namespace Yi.Framework.WeChatPay.Exceptions
|
||||||
|
{
|
||||||
|
[Serializable]
|
||||||
|
public class PayException : Exception
|
||||||
|
{
|
||||||
|
public PayException()
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
public PayException(string message) : base(message)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
public PayException(string message, Exception innerException) : base(message, innerException)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
protected PayException(SerializationInfo info, StreamingContext context) : base(info, context)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
namespace Yi.Framework.WeChatPay.Options
|
||||||
|
{
|
||||||
|
public class PayOptions
|
||||||
|
{
|
||||||
|
public string AppID { get; set; }
|
||||||
|
public string MchID { get; set; }
|
||||||
|
public string Key { get; set; }
|
||||||
|
public string NotifyUrl { get; set; }
|
||||||
|
|
||||||
|
public bool IsFileConfig { get; set; } = false;
|
||||||
|
|
||||||
|
public string ConfigPath { get; set; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using Yi.Framework.WeChatPay.Core;
|
||||||
|
using Yi.Framework.WeChatPay.Exceptions;
|
||||||
|
using Yi.Framework.WeChatPay.Options;
|
||||||
|
|
||||||
|
namespace Yi.Framework.WeChatPay.WebCore
|
||||||
|
{
|
||||||
|
public static class PayServiceExtensions
|
||||||
|
{
|
||||||
|
public static IServiceCollection AddWeChatPayService(this IServiceCollection services,Action<PayOptions> configure)
|
||||||
|
{
|
||||||
|
var option= new PayOptions();
|
||||||
|
configure(option);
|
||||||
|
if (option.IsFileConfig)
|
||||||
|
{
|
||||||
|
option=PayHelper.GetPayOptions(option.ConfigPath);
|
||||||
|
}
|
||||||
|
if (option.AppID == null)
|
||||||
|
{
|
||||||
|
throw new PayException("AppId为空值");
|
||||||
|
}
|
||||||
|
if (option.MchID == null)
|
||||||
|
{
|
||||||
|
throw new PayException("MchID为空值");
|
||||||
|
}
|
||||||
|
if (option.Key == null)
|
||||||
|
{
|
||||||
|
throw new PayException("Key为空值");
|
||||||
|
}
|
||||||
|
if (option.NotifyUrl == null)
|
||||||
|
{
|
||||||
|
throw new PayException("NotifyUrl为空值");
|
||||||
|
}
|
||||||
|
services.AddSingleton(option);
|
||||||
|
services.AddTransient<PayInvoker>();
|
||||||
|
services.AddTransient<IPayInvoker, PayInvoker>();
|
||||||
|
services.AddTransient<IPayConfig, PayConfig>();
|
||||||
|
services.AddTransient<PayHelper>();
|
||||||
|
services.AddTransient<PayApi>();
|
||||||
|
services.AddTransient<PayHttpService>();
|
||||||
|
services.AddTransient<AbstractNotify, ResultNotify>();
|
||||||
|
services.AddHttpContextAccessor();
|
||||||
|
return services;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net6.0</TargetFramework>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<Nullable>disable</Nullable>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Microsoft.AspNetCore.Http" Version="2.2.2" />
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="6.0.0" />
|
||||||
|
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="6.0.0" />
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="6.0.1" />
|
||||||
|
<PackageReference Include="NBuilder" Version="6.1.0" />
|
||||||
|
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -3,6 +3,7 @@ using Microsoft.IdentityModel.JsonWebTokens;
|
|||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
|
using System.Text.RegularExpressions;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
namespace Yi.Framework.WebCore.AttributeExtend
|
namespace Yi.Framework.WebCore.AttributeExtend
|
||||||
@@ -40,11 +41,24 @@ namespace Yi.Framework.WebCore.AttributeExtend
|
|||||||
var perList = context.HttpContext.User.Claims.Where(u => u.Type == "permission").Select(u=> u.Value.ToString().ToLower()). ToList();
|
var perList = context.HttpContext.User.Claims.Where(u => u.Type == "permission").Select(u=> u.Value.ToString().ToLower()). ToList();
|
||||||
//判断权限是否存在Redis中,或者jwt中
|
//判断权限是否存在Redis中,或者jwt中
|
||||||
|
|
||||||
//if (perList.Contains(permission.ToLower()))
|
//进行正则表达式的匹配,以code开头
|
||||||
//{
|
Regex regex = new Regex($"^{permission.ToLower()}");
|
||||||
// result = true;
|
foreach (var p in perList)
|
||||||
//}
|
{
|
||||||
result = true;
|
//过滤多余的标签
|
||||||
|
p.Replace("Entity","");
|
||||||
|
p.Replace("entity","");
|
||||||
|
if (regex.IsMatch(p))
|
||||||
|
{
|
||||||
|
result = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
//用户的增删改查直接可以user:*即可
|
||||||
|
|
||||||
|
|
||||||
|
//这里暂时全部放行即可
|
||||||
|
result = true;
|
||||||
|
|
||||||
|
|
||||||
if (!result)
|
if (!result)
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ using System.Text;
|
|||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using Yi.Framework.Model.Models;
|
using Yi.Framework.Model.Models;
|
||||||
using System.IdentityModel.Tokens.Jwt;
|
using System.IdentityModel.Tokens.Jwt;
|
||||||
|
using System.IO;
|
||||||
|
|
||||||
namespace Yi.Framework.WebCore
|
namespace Yi.Framework.WebCore
|
||||||
{
|
{
|
||||||
@@ -51,5 +52,42 @@ namespace Yi.Framework.WebCore
|
|||||||
//Name = claimlist.FirstOrDefault(u => u.Type == JwtRegisteredClaimNames.Name).Value
|
//Name = claimlist.FirstOrDefault(u => u.Type == JwtRegisteredClaimNames.Name).Value
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static void FileInlineHandle(this HttpContext httpContext, string fileName)
|
||||||
|
{
|
||||||
|
string encodeFilename = System.Web.HttpUtility.UrlEncode(fileName, System.Text.Encoding.GetEncoding("UTF-8"));
|
||||||
|
httpContext.Response.Headers.Add("Content-Disposition", "inline;filename=" + encodeFilename);
|
||||||
|
|
||||||
|
}
|
||||||
|
public static void FileAttachmentHandle(this HttpContext httpContext, string fileName)
|
||||||
|
{
|
||||||
|
string encodeFilename = System.Web.HttpUtility.UrlEncode(fileName, System.Text.Encoding.GetEncoding("UTF-8"));
|
||||||
|
httpContext.Response.Headers.Add("Content-Disposition", "attachment;filename=" + encodeFilename);
|
||||||
|
|
||||||
|
}
|
||||||
|
public static string GetLanguage(this HttpContext httpContext)
|
||||||
|
{
|
||||||
|
string res = "zh-CN";
|
||||||
|
var str = httpContext.Request.Headers["Accept-Language"].FirstOrDefault();
|
||||||
|
if (str.IsNotNull())
|
||||||
|
{
|
||||||
|
res = str.Split(",")[0];
|
||||||
|
}
|
||||||
|
return res;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public static string GetBody(this HttpContext httpContext)
|
||||||
|
{
|
||||||
|
if (httpContext.Request.Body != null)
|
||||||
|
{
|
||||||
|
httpContext.Request.EnableBuffering();
|
||||||
|
httpContext.Request.Body.Position = 0;
|
||||||
|
StreamReader stream = new StreamReader(httpContext.Request.Body);
|
||||||
|
return stream.ReadToEndAsync().GetAwaiter().GetResult();
|
||||||
|
}
|
||||||
|
return "";
|
||||||
|
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ namespace Yi.Framework.WebCore.MiddlewareExtend
|
|||||||
if (Appsettings.appBool("Redis_Enabled"))
|
if (Appsettings.appBool("Redis_Enabled"))
|
||||||
{
|
{
|
||||||
services.Configure<RedisConnOptions>(Appsettings.appConfiguration("RedisConnOptions"));
|
services.Configure<RedisConnOptions>(Appsettings.appConfiguration("RedisConnOptions"));
|
||||||
services.AddTransient<CacheClientDB>();
|
services.AddSingleton<CacheClientDB>();
|
||||||
}
|
}
|
||||||
return services;
|
return services;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ namespace Yi.Framework.WebCore.MiddlewareExtend
|
|||||||
{
|
{
|
||||||
public static class SqlsugarExtension
|
public static class SqlsugarExtension
|
||||||
{
|
{
|
||||||
public static void AddSqlsugarServer(this IServiceCollection services)
|
public static void AddSqlsugarServer(this IServiceCollection services, Action<SqlSugarClient> action = null)
|
||||||
{
|
{
|
||||||
|
|
||||||
|
|
||||||
@@ -61,6 +61,10 @@ namespace Yi.Framework.WebCore.MiddlewareExtend
|
|||||||
},
|
},
|
||||||
db =>
|
db =>
|
||||||
{
|
{
|
||||||
|
if (action.IsNotNull())
|
||||||
|
{
|
||||||
|
action(db);
|
||||||
|
}
|
||||||
|
|
||||||
db.Aop.DataExecuting = (oldValue, entityInfo) =>
|
db.Aop.DataExecuting = (oldValue, entityInfo) =>
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -34,7 +34,7 @@ namespace Yi.Framework.WebCore.MiddlewareExtend
|
|||||||
var apiXmlPath = Path.Combine(basePath, @"SwaggerDoc.xml");//控制器层注释
|
var apiXmlPath = Path.Combine(basePath, @"SwaggerDoc.xml");//控制器层注释
|
||||||
//var entityXmlPath = Path.Combine(basePath, @"SwaggerDoc.xml");//实体注释
|
//var entityXmlPath = Path.Combine(basePath, @"SwaggerDoc.xml");//实体注释
|
||||||
//c.IncludeXmlComments(apiXmlPath, true);//true表示显示控制器注释
|
//c.IncludeXmlComments(apiXmlPath, true);//true表示显示控制器注释
|
||||||
c.IncludeXmlComments(apiXmlPath,true);
|
c.IncludeXmlComments(apiXmlPath, true);
|
||||||
|
|
||||||
//添加控制器注释
|
//添加控制器注释
|
||||||
//c.DocumentFilter<SwaggerDocTag>();
|
//c.DocumentFilter<SwaggerDocTag>();
|
||||||
@@ -42,25 +42,40 @@ namespace Yi.Framework.WebCore.MiddlewareExtend
|
|||||||
//添加header验证信息
|
//添加header验证信息
|
||||||
//c.OperationFilter<SwaggerHeader>();
|
//c.OperationFilter<SwaggerHeader>();
|
||||||
//var security = new Dictionary<string, IEnumerable<string>> { { "Bearer", new string[] { } }, };
|
//var security = new Dictionary<string, IEnumerable<string>> { { "Bearer", new string[] { } }, };
|
||||||
|
c.AddSecurityDefinition("JwtBearer", new OpenApiSecurityScheme()
|
||||||
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
|
|
||||||
{
|
{
|
||||||
Description = "文本框里输入从服务器获取的Token。格式为:Bearer + 空格+token",//JWT授权(数据将在请求头中进行传输) 参数结构: \"Authorization: Bearer {token}\"
|
Description = "直接输入Token即可",
|
||||||
Name = "Authorization",////jwt默认的参数名称
|
Name = "Authorization",
|
||||||
In = ParameterLocation.Header,////jwt默认存放Authorization信息的位置(请求头中)
|
In = ParameterLocation.Header,
|
||||||
Type = SecuritySchemeType.ApiKey,
|
Type = SecuritySchemeType.Http,
|
||||||
|
Scheme = "bearer"
|
||||||
});
|
});
|
||||||
c.AddSecurityRequirement(new OpenApiSecurityRequirement
|
var scheme = new OpenApiSecurityScheme()
|
||||||
{
|
{
|
||||||
{ new OpenApiSecurityScheme
|
Reference = new OpenApiReference() { Type = ReferenceType.SecurityScheme, Id = "JwtBearer" }
|
||||||
{
|
};
|
||||||
Reference = new OpenApiReference()
|
c.AddSecurityRequirement(new OpenApiSecurityRequirement()
|
||||||
{
|
{
|
||||||
Id = "Bearer",
|
[scheme] = new string[0]
|
||||||
Type = ReferenceType.SecurityScheme
|
|
||||||
}
|
|
||||||
}, Array.Empty<string>() }
|
|
||||||
});
|
});
|
||||||
|
//c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
|
||||||
|
//{
|
||||||
|
// Description = "文本框里输入从服务器获取的Token。格式为:Bearer + 空格+token",//JWT授权(数据将在请求头中进行传输) 参数结构: \"Authorization: Bearer {token}\"
|
||||||
|
// Name = "Authorization",////jwt默认的参数名称
|
||||||
|
// In = ParameterLocation.Header,////jwt默认存放Authorization信息的位置(请求头中)
|
||||||
|
// Type = SecuritySchemeType.ApiKey,
|
||||||
|
//});
|
||||||
|
//c.AddSecurityRequirement(new OpenApiSecurityRequirement
|
||||||
|
//{
|
||||||
|
// { new OpenApiSecurityScheme
|
||||||
|
// {
|
||||||
|
// Reference = new OpenApiReference()
|
||||||
|
// {
|
||||||
|
// Id = "Bearer",
|
||||||
|
// Type = ReferenceType.SecurityScheme
|
||||||
|
// }
|
||||||
|
// }, Array.Empty<string>() }
|
||||||
|
//});
|
||||||
|
|
||||||
//c.AddServer(new OpenApiServer()
|
//c.AddServer(new OpenApiServer()
|
||||||
//{
|
//{
|
||||||
|
|||||||
@@ -34,10 +34,6 @@
|
|||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ProjectReference Include="..\Yi.Framework.Core\Yi.Framework.Core.csproj" />
|
<ProjectReference Include="..\Yi.Framework.Core\Yi.Framework.Core.csproj" />
|
||||||
<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.Repository\Yi.Framework.Repository.csproj" />
|
|
||||||
<ProjectReference Include="..\Yi.Framework.Service\Yi.Framework.Service.csproj" />
|
<ProjectReference Include="..\Yi.Framework.Service\Yi.Framework.Service.csproj" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
|||||||
@@ -41,9 +41,11 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Yi.Framework.Job", "Yi.Fram
|
|||||||
EndProject
|
EndProject
|
||||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Yi.Framework.SMSProcessor", "Yi.Framework.SMSProcessor\Yi.Framework.SMSProcessor.csproj", "{7C58FB7C-9AB5-47CF-ACEB-B784CF820E7E}"
|
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Yi.Framework.SMSProcessor", "Yi.Framework.SMSProcessor\Yi.Framework.SMSProcessor.csproj", "{7C58FB7C-9AB5-47CF-ACEB-B784CF820E7E}"
|
||||||
EndProject
|
EndProject
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Yi.Framework.Repository", "Yi.Framework.Repository\Yi.Framework.Repository.csproj", "{DA96B62F-2D4C-4AFB-937C-5AEA1119A129}"
|
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Yi.Framework.Repository", "Yi.Framework.Repository\Yi.Framework.Repository.csproj", "{DA96B62F-2D4C-4AFB-937C-5AEA1119A129}"
|
||||||
EndProject
|
EndProject
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Yi.Framework.Language", "Yi.Framework.Language\Yi.Framework.Language.csproj", "{3047069B-4084-461F-BC9F-023BC60401D1}"
|
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Yi.Framework.Language", "Yi.Framework.Language\Yi.Framework.Language.csproj", "{3047069B-4084-461F-BC9F-023BC60401D1}"
|
||||||
|
EndProject
|
||||||
|
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Yi.Framework.WeChatPay", "Yi.Framework.WeChatPay\Yi.Framework.WeChatPay.csproj", "{C307189D-C42C-4C09-BB65-5A386C9F182B}"
|
||||||
EndProject
|
EndProject
|
||||||
Global
|
Global
|
||||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||||
@@ -115,6 +117,10 @@ Global
|
|||||||
{3047069B-4084-461F-BC9F-023BC60401D1}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
{3047069B-4084-461F-BC9F-023BC60401D1}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
{3047069B-4084-461F-BC9F-023BC60401D1}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
{3047069B-4084-461F-BC9F-023BC60401D1}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
{3047069B-4084-461F-BC9F-023BC60401D1}.Release|Any CPU.Build.0 = Release|Any CPU
|
{3047069B-4084-461F-BC9F-023BC60401D1}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
{C307189D-C42C-4C09-BB65-5A386C9F182B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
|
{C307189D-C42C-4C09-BB65-5A386C9F182B}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{C307189D-C42C-4C09-BB65-5A386C9F182B}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
{C307189D-C42C-4C09-BB65-5A386C9F182B}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
EndGlobalSection
|
EndGlobalSection
|
||||||
GlobalSection(SolutionProperties) = preSolution
|
GlobalSection(SolutionProperties) = preSolution
|
||||||
HideSolutionNode = FALSE
|
HideSolutionNode = FALSE
|
||||||
@@ -136,6 +142,7 @@ Global
|
|||||||
{7C58FB7C-9AB5-47CF-ACEB-B784CF820E7E} = {D6B44435-EAFA-4D55-90D0-3AF80485FB83}
|
{7C58FB7C-9AB5-47CF-ACEB-B784CF820E7E} = {D6B44435-EAFA-4D55-90D0-3AF80485FB83}
|
||||||
{DA96B62F-2D4C-4AFB-937C-5AEA1119A129} = {DB2506F5-05FD-4E76-940E-41D7AA148550}
|
{DA96B62F-2D4C-4AFB-937C-5AEA1119A129} = {DB2506F5-05FD-4E76-940E-41D7AA148550}
|
||||||
{3047069B-4084-461F-BC9F-023BC60401D1} = {9ABAF6B1-6C02-498A-90A2-ABC1140CF89A}
|
{3047069B-4084-461F-BC9F-023BC60401D1} = {9ABAF6B1-6C02-498A-90A2-ABC1140CF89A}
|
||||||
|
{C307189D-C42C-4C09-BB65-5A386C9F182B} = {9ABAF6B1-6C02-498A-90A2-ABC1140CF89A}
|
||||||
EndGlobalSection
|
EndGlobalSection
|
||||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||||
SolutionGuid = {1ED77A6E-377F-4EEF-A3D0-D65C94657DAF}
|
SolutionGuid = {1ED77A6E-377F-4EEF-A3D0-D65C94657DAF}
|
||||||
|
|||||||
@@ -1,22 +1,11 @@
|
|||||||
import myaxios from '@/util/myaxios'
|
import myaxios from '@/util/myaxios'
|
||||||
|
import {objctToDic} from '@/util/objctHandle'
|
||||||
export default {
|
export default {
|
||||||
getList() {
|
getList() {
|
||||||
return myaxios({
|
return myaxios({
|
||||||
url: '/Role/GetList',
|
url: '/Role/GetList',
|
||||||
method: 'post',
|
method: 'post',
|
||||||
data: {
|
data: objctToDic()
|
||||||
parameters: [
|
|
||||||
{
|
|
||||||
key: "isDeleted",
|
|
||||||
value: "0",
|
|
||||||
type: 0
|
|
||||||
|
|
||||||
}
|
|
||||||
],
|
|
||||||
orderBys: [
|
|
||||||
"id"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
giveRoleSetMenu(roleList, menuList) {
|
giveRoleSetMenu(roleList, menuList) {
|
||||||
|
|||||||
@@ -1,14 +1,5 @@
|
|||||||
import myaxios from '@/util/myaxios'
|
import myaxios from '@/util/myaxios'
|
||||||
export default {
|
export default {
|
||||||
SetRoleByUser(userIds, roleIds) {
|
|
||||||
return myaxios({
|
|
||||||
url: '/User/SetRoleByUser',
|
|
||||||
method: 'post',
|
|
||||||
data: { "ids1": userIds, "ids2": roleIds }
|
|
||||||
})
|
|
||||||
},
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
GetUserInRolesByHttpUser() {
|
GetUserInRolesByHttpUser() {
|
||||||
return myaxios({
|
return myaxios({
|
||||||
@@ -28,4 +19,12 @@ export default {
|
|||||||
method: 'get'
|
method: 'get'
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
|
GiveUserSetRole(UserIds,RoleIds)
|
||||||
|
{
|
||||||
|
return myaxios({
|
||||||
|
url: `/User/GiveUserSetRole`,
|
||||||
|
method: 'put',
|
||||||
|
data:{UserIds,RoleIds}
|
||||||
|
})
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,22 +1,11 @@
|
|||||||
import myaxios from '@/util/myaxios'
|
import myaxios from '@/util/myaxios'
|
||||||
|
import {objctToDic} from '@/util/objctHandle'
|
||||||
export default {
|
export default {
|
||||||
getItem(url) {
|
getItem(url) {
|
||||||
return myaxios({
|
return myaxios({
|
||||||
url: url,
|
url: url,
|
||||||
method: 'post',
|
method: 'post',
|
||||||
data: {
|
data: objctToDic()
|
||||||
parameters: [
|
|
||||||
{
|
|
||||||
key: "isDeleted",
|
|
||||||
value: "0",
|
|
||||||
type: 0
|
|
||||||
|
|
||||||
}
|
|
||||||
],
|
|
||||||
orderBys: [
|
|
||||||
"id"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
addItem(url, data) {
|
addItem(url, data) {
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
<v-avatar :size="size" >
|
<v-avatar :size="size" >
|
||||||
<!-- <img src="https://z3.ax1x.com/2021/05/09/gJadhD.jpg" /> -->
|
<!-- <img src="https://z3.ax1x.com/2021/05/09/gJadhD.jpg" /> -->
|
||||||
<img
|
<img
|
||||||
:src="baseurl +'/image/'+$store.state.user.user.icon"
|
:src="baseurl +'/image/'+$store.state.user.user.user.icon"
|
||||||
/>
|
/>
|
||||||
</v-avatar>
|
</v-avatar>
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
@@ -58,6 +58,8 @@ export default {
|
|||||||
watch:{
|
watch:{
|
||||||
select:{//深度监听,可监听到对象、数组的变化
|
select:{//深度监听,可监听到对象、数组的变化
|
||||||
handler(val, oldVal){
|
handler(val, oldVal){
|
||||||
|
console.log(oldVal)
|
||||||
|
console.log(val)
|
||||||
this.$emit("select",val);
|
this.$emit("select",val);
|
||||||
},
|
},
|
||||||
deep:true
|
deep:true
|
||||||
|
|||||||
@@ -24,7 +24,7 @@
|
|||||||
></v-text-field>
|
></v-text-field>
|
||||||
|
|
||||||
<v-btn
|
<v-btn
|
||||||
v-if="axiosUrls.add != null"
|
v-if="btnEnable.add==true"
|
||||||
color="primary"
|
color="primary"
|
||||||
dark
|
dark
|
||||||
class="mb-2 mx-2"
|
class="mb-2 mx-2"
|
||||||
@@ -35,7 +35,7 @@
|
|||||||
|
|
||||||
<!-- 添加提示框 -->
|
<!-- 添加提示框 -->
|
||||||
<v-dialog
|
<v-dialog
|
||||||
v-if="axiosUrls.add != null"
|
v-if="btnEnable.add ==true"
|
||||||
v-model="dialog"
|
v-model="dialog"
|
||||||
max-width="500px"
|
max-width="500px"
|
||||||
>
|
>
|
||||||
@@ -72,7 +72,7 @@
|
|||||||
</v-dialog>
|
</v-dialog>
|
||||||
|
|
||||||
<v-btn
|
<v-btn
|
||||||
v-if="axiosUrls.del != null"
|
v-if="btnEnable.del == true"
|
||||||
color="secondary"
|
color="secondary"
|
||||||
class="mb-2"
|
class="mb-2"
|
||||||
@click="deleteItem(null)"
|
@click="deleteItem(null)"
|
||||||
@@ -87,14 +87,14 @@
|
|||||||
<slot name="action" :item="item"></slot>
|
<slot name="action" :item="item"></slot>
|
||||||
|
|
||||||
<v-icon
|
<v-icon
|
||||||
v-if="axiosUrls.update != null"
|
v-if="btnEnable.update ==true"
|
||||||
small
|
small
|
||||||
class="mr-2"
|
class="mr-2"
|
||||||
@click="editItem(item)"
|
@click="editItem(item)"
|
||||||
>
|
>
|
||||||
mdi-pencil
|
mdi-pencil
|
||||||
</v-icon>
|
</v-icon>
|
||||||
<v-icon v-if="axiosUrls.del != null" small @click="deleteItem(item)">
|
<v-icon v-if="btnEnable.del ==true" small @click="deleteItem(item)">
|
||||||
mdi-delete
|
mdi-delete
|
||||||
</v-icon>
|
</v-icon>
|
||||||
</template>
|
</template>
|
||||||
@@ -119,6 +119,9 @@ export default {
|
|||||||
axiosUrls: {
|
axiosUrls: {
|
||||||
type: Object,
|
type: Object,
|
||||||
},
|
},
|
||||||
|
btnEnable: {
|
||||||
|
type: Object,
|
||||||
|
},
|
||||||
},
|
},
|
||||||
data: () => ({
|
data: () => ({
|
||||||
page: 1,
|
page: 1,
|
||||||
@@ -166,7 +169,7 @@ export default {
|
|||||||
});
|
});
|
||||||
},
|
},
|
||||||
initialize() {
|
initialize() {
|
||||||
if(this.axiosUrls.get!=undefined && this.axiosUrls.get!=null )
|
if(this.btnEnable.get==true )
|
||||||
{
|
{
|
||||||
this.dataInit(this.axiosUrls.get)
|
this.dataInit(this.axiosUrls.get)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -52,11 +52,15 @@
|
|||||||
hoverable
|
hoverable
|
||||||
item-text="menuName"
|
item-text="menuName"
|
||||||
>
|
>
|
||||||
|
<template v-slot:prepend="{ item }">
|
||||||
|
<v-icon>
|
||||||
|
{{ item.menuIcon }}
|
||||||
|
</v-icon>
|
||||||
|
</template>
|
||||||
<template v-slot:append="{ item }">
|
<template v-slot:append="{ item }">
|
||||||
<v-btn class="mr-2">编号:{{ item.id }}</v-btn>
|
<app-btn v-show="item.menuType==1" class="mr-2" color="secondary"> 权限:{{ item.permissionCode }}</app-btn>
|
||||||
<v-btn class="mr-2">权限:{{ item.permissionCode }}</v-btn>
|
|
||||||
<!-- <v-btn class="mr-2">图标:{{ item.icon }}</v-btn> -->
|
<!-- <v-btn class="mr-2">图标:{{ item.icon }}</v-btn> -->
|
||||||
<!-- <v-btn class="mr-2">路由:{{ item.router }}</v-btn> -->
|
<app-btn v-show="item.menuType==0" class="mr-2" >路由:{{ item.router }}</app-btn>
|
||||||
<!-- <v-btn v-if="item.mould" class="mr-2">接口名:{{ item.mould.mould_name }}</v-btn>
|
<!-- <v-btn v-if="item.mould" class="mr-2">接口名:{{ item.mould.mould_name }}</v-btn>
|
||||||
<v-btn v-if="item.mould" class="mr-2" color="secondary">接口地址:{{ item.mould.url }}</v-btn> -->
|
<v-btn v-if="item.mould" class="mr-2" color="secondary">接口地址:{{ item.mould.url }}</v-btn> -->
|
||||||
<!-- <ccCombobox
|
<!-- <ccCombobox
|
||||||
@@ -102,9 +106,10 @@ export default {
|
|||||||
editedItem: {},
|
editedItem: {},
|
||||||
editedIndex: -1,
|
editedIndex: -1,
|
||||||
defaultItem: {
|
defaultItem: {
|
||||||
// icon: "mdi-start",
|
menuIcon: "mdi-view-dashboard",
|
||||||
permissionCode: "test",
|
permissionCode: "",
|
||||||
menuName: "管理",
|
menuName: "",
|
||||||
|
router:"",
|
||||||
parentId: 0,
|
parentId: 0,
|
||||||
MenuType:0
|
MenuType:0
|
||||||
},
|
},
|
||||||
@@ -122,21 +127,16 @@ export default {
|
|||||||
this.$refs.tree.updateAll(true);
|
this.$refs.tree.updateAll(true);
|
||||||
},
|
},
|
||||||
|
|
||||||
// setMould(item) {
|
|
||||||
// menuApi.SetMouldByMenu(item.id, this.mouldSelect[0].id).then((resp) => {
|
|
||||||
// this.$dialog.notify.info(resp.msg, {
|
|
||||||
// position: "top-right",
|
|
||||||
// timeout: 5000,
|
|
||||||
// });
|
|
||||||
// this.init();
|
|
||||||
// });
|
|
||||||
// },
|
|
||||||
|
|
||||||
getSelect(data) {
|
getSelect(data) {
|
||||||
this.mouldSelect = data;
|
this.mouldSelect = data;
|
||||||
},
|
},
|
||||||
async deleteItem(item) {
|
async deleteItem(item) {
|
||||||
this.editedIndex = 1;
|
if(item!=null)
|
||||||
|
{
|
||||||
|
this.editedIndex = 1;
|
||||||
|
}
|
||||||
|
|
||||||
this.editedItem = Object.assign({}, item);
|
this.editedItem = Object.assign({}, item);
|
||||||
var p = await this.$dialog.warning({
|
var p = await this.$dialog.warning({
|
||||||
text: "你确定要删除此条记录吗??",
|
text: "你确定要删除此条记录吗??",
|
||||||
@@ -155,7 +155,7 @@ export default {
|
|||||||
if (this.editedIndex > -1) {
|
if (this.editedIndex > -1) {
|
||||||
Ids.push(this.editedItem.id);
|
Ids.push(this.editedItem.id);
|
||||||
} else {
|
} else {
|
||||||
this.selection.forEach(function (item) {
|
this.selection.forEach( (item) =>{
|
||||||
Ids.push(item.id);
|
Ids.push(item.id);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -201,6 +201,7 @@ export default {
|
|||||||
selection: {
|
selection: {
|
||||||
//深度监听,可监听到对象、数组的变化
|
//深度监听,可监听到对象、数组的变化
|
||||||
handler(val, oldVal) {
|
handler(val, oldVal) {
|
||||||
|
|
||||||
this.$emit("selection", val);
|
this.$emit("selection", val);
|
||||||
},
|
},
|
||||||
deep: true,
|
deep: true,
|
||||||
|
|||||||
@@ -1,15 +1,6 @@
|
|||||||
<template>
|
<template>
|
||||||
<v-navigation-drawer
|
<v-navigation-drawer id="default-drawer" v-model="$store.state.home.drawer" :dark="dark" :right="$vuetify.rtl"
|
||||||
id="default-drawer"
|
:src="drawerImage ? image : ''" :mini-variant.sync="$store.state.home.mini" mini-variant-width="80" app width="260">
|
||||||
v-model="$store.state.home.drawer"
|
|
||||||
:dark="dark"
|
|
||||||
:right="$vuetify.rtl"
|
|
||||||
:src="drawerImage ? image : ''"
|
|
||||||
:mini-variant.sync="$store.state.home.mini"
|
|
||||||
mini-variant-width="80"
|
|
||||||
app
|
|
||||||
width="260"
|
|
||||||
>
|
|
||||||
<template v-if="drawerImage" #img="props">
|
<template v-if="drawerImage" #img="props">
|
||||||
<v-img :key="image" :gradient="gradient" v-bind="props" />
|
<v-img :key="image" :gradient="gradient" v-bind="props" />
|
||||||
</template>
|
</template>
|
||||||
@@ -24,13 +15,7 @@
|
|||||||
|
|
||||||
<template #append>
|
<template #append>
|
||||||
<div class="pa-4 text-center">
|
<div class="pa-4 text-center">
|
||||||
<app-btn
|
<app-btn class="text-none mb-4" color="white" href="https://vuetifyjs.com" small text>
|
||||||
class="text-none mb-4"
|
|
||||||
color="white"
|
|
||||||
href="https://vuetifyjs.com"
|
|
||||||
small
|
|
||||||
text
|
|
||||||
>
|
|
||||||
Documentation
|
Documentation
|
||||||
</app-btn>
|
</app-btn>
|
||||||
|
|
||||||
@@ -49,180 +34,19 @@
|
|||||||
<script>
|
<script>
|
||||||
// Utilities
|
// Utilities
|
||||||
// import { get, sync } from 'vuex-pathify'
|
// import { get, sync } from 'vuex-pathify'
|
||||||
import userApi from "@/api/userApi";
|
import store from "@/store/index.js";
|
||||||
|
import { toTree } from "@/util/menuHandle";
|
||||||
export default {
|
export default {
|
||||||
methods: {
|
methods: {
|
||||||
init() {
|
init() {
|
||||||
//这里动态获取菜单,暂时写死
|
const menus = store.state.user.user.menus.filter((m) => {
|
||||||
// userApi.GetMenuByHttpUser().then((resp) => {
|
return m.menuType == 0;
|
||||||
// this.items = resp.data.children;
|
});
|
||||||
// });
|
this.items = toTree(menus);
|
||||||
this.items =
|
|
||||||
|
|
||||||
[
|
|
||||||
{
|
|
||||||
icon: "mdi-view-dashboard",
|
|
||||||
router: "/",
|
|
||||||
menu_name: "首页",
|
|
||||||
roles: null,
|
|
||||||
mould: null,
|
|
||||||
is_top: 0,
|
|
||||||
sort: 0,
|
|
||||||
is_show: 1,
|
|
||||||
parentId: 1,
|
|
||||||
children: null,
|
|
||||||
id: 2,
|
|
||||||
is_delete: 0,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
icon: "mdi-account-box-multiple",
|
|
||||||
router: null,
|
|
||||||
menu_name: "用户角色管理",
|
|
||||||
roles: null,
|
|
||||||
mould: null,
|
|
||||||
is_top: 0,
|
|
||||||
sort: 0,
|
|
||||||
is_show: 1,
|
|
||||||
parentId: 1,
|
|
||||||
children: [
|
|
||||||
{
|
|
||||||
icon: "mdi-account-box",
|
|
||||||
router: "/AdmUser/",
|
|
||||||
menu_name: "用户管理",
|
|
||||||
roles: null,
|
|
||||||
mould: null,
|
|
||||||
is_top: 0,
|
|
||||||
sort: 0,
|
|
||||||
is_show: 1,
|
|
||||||
parentId: 3,
|
|
||||||
children: null,
|
|
||||||
id: 4,
|
|
||||||
is_delete: 0,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
icon: "mdi-account-circle",
|
|
||||||
router: "/admrole/",
|
|
||||||
menu_name: "角色管理",
|
|
||||||
roles: null,
|
|
||||||
mould: null,
|
|
||||||
is_top: 0,
|
|
||||||
sort: 0,
|
|
||||||
is_show: 1,
|
|
||||||
parentId: 3,
|
|
||||||
children: null,
|
|
||||||
id: 9,
|
|
||||||
is_delete: 0,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
id: 3,
|
|
||||||
is_delete: 0,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
icon: "mdi-account-cash",
|
|
||||||
router: null,
|
|
||||||
menu_name: "角色接口管理",
|
|
||||||
roles: null,
|
|
||||||
mould: null,
|
|
||||||
is_top: 0,
|
|
||||||
sort: 0,
|
|
||||||
is_show: 1,
|
|
||||||
parentId: 1,
|
|
||||||
children: [
|
|
||||||
{
|
|
||||||
icon: "mdi-clipboard-check-multiple",
|
|
||||||
router: "/AdmMenu/",
|
|
||||||
menu_name: "菜单管理",
|
|
||||||
roles: null,
|
|
||||||
mould: null,
|
|
||||||
is_top: 0,
|
|
||||||
sort: 0,
|
|
||||||
is_show: 1,
|
|
||||||
parentId: 14,
|
|
||||||
children: null,
|
|
||||||
id: 15,
|
|
||||||
is_delete: 0,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
icon: "mdi-circle-slice-8",
|
|
||||||
router: "/admMould/",
|
|
||||||
menu_name: "接口管理",
|
|
||||||
roles: null,
|
|
||||||
mould: null,
|
|
||||||
is_top: 0,
|
|
||||||
sort: 0,
|
|
||||||
is_show: 1,
|
|
||||||
parentId: 14,
|
|
||||||
children: null,
|
|
||||||
id: 20,
|
|
||||||
is_delete: 0,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
icon: "mdi-clipboard-account",
|
|
||||||
router: "/admRoleMenu/",
|
|
||||||
menu_name: "角色菜单分配管理",
|
|
||||||
roles: null,
|
|
||||||
mould: null,
|
|
||||||
is_top: 0,
|
|
||||||
sort: 0,
|
|
||||||
is_show: 1,
|
|
||||||
parentId: 14,
|
|
||||||
children: null,
|
|
||||||
id: 25,
|
|
||||||
is_delete: 0,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
id: 14,
|
|
||||||
is_delete: 0,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
icon: "mdi-clipboard-flow-outline",
|
|
||||||
router: null,
|
|
||||||
menu_name: "路由管理",
|
|
||||||
roles: null,
|
|
||||||
mould: null,
|
|
||||||
is_top: 0,
|
|
||||||
sort: 0,
|
|
||||||
is_show: 1,
|
|
||||||
parentId: 1,
|
|
||||||
children: [
|
|
||||||
{
|
|
||||||
icon: "mdi-account-eye",
|
|
||||||
router: "/userinfo/",
|
|
||||||
menu_name: "用户信息",
|
|
||||||
roles: null,
|
|
||||||
mould: null,
|
|
||||||
is_top: 0,
|
|
||||||
sort: 0,
|
|
||||||
is_show: 1,
|
|
||||||
parentId: 26,
|
|
||||||
children: null,
|
|
||||||
id: 27,
|
|
||||||
is_delete: 0,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
icon: "mdi-account-eye",
|
|
||||||
router: "/pan",
|
|
||||||
menu_name: "云盘管理",
|
|
||||||
roles: null,
|
|
||||||
mould: null,
|
|
||||||
is_top: 0,
|
|
||||||
sort: 0,
|
|
||||||
is_show: 1,
|
|
||||||
parentId: 26,
|
|
||||||
children: null,
|
|
||||||
id: 28,
|
|
||||||
is_delete: 0,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
id: 26,
|
|
||||||
is_delete: 0,
|
|
||||||
},
|
|
||||||
]
|
|
||||||
|
|
||||||
},
|
},
|
||||||
logout() {
|
logout() {
|
||||||
this.$store.dispatch("Logout");
|
this.$store.dispatch("Logout")
|
||||||
this.$router.push({ path: "/login" });
|
this.$router.push({ path: "/login/" });
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
created() {
|
created() {
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
<template>
|
<template>
|
||||||
<v-list-group :group="group" :prepend-icon="item.icon" eager v-bind="$attrs">
|
<v-list-group :group="group" :prepend-icon="item.menuIcon" eager v-bind="$attrs">
|
||||||
<template v-slot:activator>
|
<template v-slot:activator>
|
||||||
<v-list-item-icon
|
<v-list-item-icon
|
||||||
v-if="!item.icon && !item.avatar"
|
v-if="!item.menuIcon && !item.avatar"
|
||||||
class="text-caption text-uppercase text-center my-2 align-self-center"
|
class="text-caption text-uppercase text-center my-2 align-self-center"
|
||||||
style="margin-top: 14px"
|
style="margin-top: 14px"
|
||||||
>
|
>
|
||||||
@@ -13,8 +13,8 @@
|
|||||||
<v-img :src="item.avatar" />
|
<v-img :src="item.avatar" />
|
||||||
</v-list-item-avatar>
|
</v-list-item-avatar>
|
||||||
|
|
||||||
<v-list-item-content v-if="item.menu_name">
|
<v-list-item-content v-if="item.menuName">
|
||||||
<v-list-item-title v-text="item.menu_name" />
|
<v-list-item-title v-text="item.menuName" />
|
||||||
</v-list-item-content>
|
</v-list-item-content>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
@@ -57,7 +57,7 @@ export default {
|
|||||||
return this.genGroup(this.item.children);
|
return this.genGroup(this.item.children);
|
||||||
},
|
},
|
||||||
title() {
|
title() {
|
||||||
const matches = this.item.menu_name.match(/\b(\w)/g);
|
const matches = this.item.menuName.match(/\b(\w)/g);
|
||||||
if (matches != null) {
|
if (matches != null) {
|
||||||
return matches.join("");
|
return matches.join("");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,7 +11,7 @@
|
|||||||
v-on="$listeners"
|
v-on="$listeners"
|
||||||
>
|
>
|
||||||
<v-list-item-icon
|
<v-list-item-icon
|
||||||
v-if="!item.icon"
|
v-if="!item.menuIcon"
|
||||||
class="text-caption text-uppercase justify-center ml-1 my-2 align-self-center"
|
class="text-caption text-uppercase justify-center ml-1 my-2 align-self-center"
|
||||||
>
|
>
|
||||||
{{ title }}
|
{{ title }}
|
||||||
@@ -22,14 +22,14 @@
|
|||||||
</v-list-item-avatar>
|
</v-list-item-avatar>
|
||||||
|
|
||||||
<v-list-item-icon
|
<v-list-item-icon
|
||||||
v-if="item.icon"
|
v-if="item.menuIcon"
|
||||||
class="my-2 align-self-center"
|
class="my-2 align-self-center"
|
||||||
>
|
>
|
||||||
<v-icon v-text="item.icon" />
|
<v-icon v-text="item.menuIcon" />
|
||||||
</v-list-item-icon>
|
</v-list-item-icon>
|
||||||
|
|
||||||
<v-list-item-content v-if="item.menu_name">
|
<v-list-item-content v-if="item.menuName">
|
||||||
<v-list-item-title v-text="item.menu_name" />
|
<v-list-item-title v-text="item.menuName" />
|
||||||
</v-list-item-content>
|
</v-list-item-content>
|
||||||
</v-list-item>
|
</v-list-item>
|
||||||
</template>
|
</template>
|
||||||
@@ -47,7 +47,7 @@
|
|||||||
|
|
||||||
computed: {
|
computed: {
|
||||||
title () {
|
title () {
|
||||||
const matches = this.item.menu_name.match(/\b(\w)/g)
|
const matches = this.item.menuName.match(/\b(\w)/g)
|
||||||
if(matches!=null)
|
if(matches!=null)
|
||||||
{
|
{
|
||||||
return matches.join('')
|
return matches.join('')
|
||||||
|
|||||||
@@ -4,6 +4,10 @@ import store from './store/index'
|
|||||||
|
|
||||||
|
|
||||||
router.beforeEach((to, from, next) => {
|
router.beforeEach((to, from, next) => {
|
||||||
|
|
||||||
|
// console.log(to)
|
||||||
|
// console.log(from)
|
||||||
|
// console.log(next)
|
||||||
const user = store.state.user.user; //获取是有user
|
const user = store.state.user.user; //获取是有user
|
||||||
if (!user) { //如果没有登入
|
if (!user) { //如果没有登入
|
||||||
if (to.path == '/login/' || to.path == '/register/' || to.path == '/reset_password/' || to.path == '/qq/') {
|
if (to.path == '/login/' || to.path == '/register/' || to.path == '/reset_password/' || to.path == '/qq/') {
|
||||||
|
|||||||
@@ -38,9 +38,13 @@ const mutations = { //变化//载荷
|
|||||||
},
|
},
|
||||||
SET_USER(state, user) {
|
SET_USER(state, user) {
|
||||||
state.user = user
|
state.user = user
|
||||||
console.log(user)
|
|
||||||
setUser(user)
|
setUser(user)
|
||||||
},
|
},
|
||||||
|
SET_NEW_USER(state, userInfo) {
|
||||||
|
state.user.user = userInfo
|
||||||
|
setUser(state.user)
|
||||||
|
},
|
||||||
|
|
||||||
SetGradient(state, gradient) {
|
SetGradient(state, gradient) {
|
||||||
state.drawer.gradient = gradient
|
state.drawer.gradient = gradient
|
||||||
},
|
},
|
||||||
@@ -87,19 +91,25 @@ const actions = { //动作
|
|||||||
|
|
||||||
|
|
||||||
accountApi.getUserAllInfo().then(resp2=>{
|
accountApi.getUserAllInfo().then(resp2=>{
|
||||||
commit('SET_USER', resp2.data.user)
|
commit('SET_USER', resp2.data)
|
||||||
|
|
||||||
var code=[];
|
var code=[];
|
||||||
resp2.data.menus.forEach(element => {
|
resp2.data.menus.forEach(element => {
|
||||||
code.push(element.permissionCode)
|
if(element.permissionCode!="")
|
||||||
|
{
|
||||||
|
code.push(element.permissionCode)
|
||||||
|
}
|
||||||
|
|
||||||
});
|
});
|
||||||
commit('SET_PER', code)
|
commit('SET_PER', code)
|
||||||
|
|
||||||
resolv(resp)
|
resolv(resp)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
resolv(resp)
|
||||||
|
}
|
||||||
}).catch(error => {
|
}).catch(error => {
|
||||||
reject(error)
|
reject(error)
|
||||||
})
|
})
|
||||||
|
|||||||
81
Yi.Vue2.x/src/util/btnHandle.js
Normal file
81
Yi.Vue2.x/src/util/btnHandle.js
Normal file
@@ -0,0 +1,81 @@
|
|||||||
|
import store from '../store/index'
|
||||||
|
//匹配按钮,判断是否有按钮存在
|
||||||
|
|
||||||
|
function getBtn(par) {
|
||||||
|
var axiosEnable = {
|
||||||
|
get: false,
|
||||||
|
update: false,
|
||||||
|
del: false,
|
||||||
|
add: false,
|
||||||
|
};
|
||||||
|
const per = store.state.user.per;
|
||||||
|
switch (par) {
|
||||||
|
case "user":
|
||||||
|
per.forEach(p => {
|
||||||
|
if(p=="user:get")
|
||||||
|
{
|
||||||
|
axiosEnable.get=true;
|
||||||
|
}
|
||||||
|
else if(p=="user:update")
|
||||||
|
{
|
||||||
|
axiosEnable.update=true;
|
||||||
|
}
|
||||||
|
else if(p=="user:del")
|
||||||
|
{
|
||||||
|
axiosEnable.del=true;
|
||||||
|
}
|
||||||
|
else if(p=="user:add")
|
||||||
|
{
|
||||||
|
axiosEnable.add=true;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
case "role":
|
||||||
|
per.forEach(p => {
|
||||||
|
if(p=="role:get")
|
||||||
|
{
|
||||||
|
axiosEnable.get=true;
|
||||||
|
}
|
||||||
|
else if(p=="role:update")
|
||||||
|
{
|
||||||
|
axiosEnable.update=true;
|
||||||
|
}
|
||||||
|
else if(p=="role:del")
|
||||||
|
{
|
||||||
|
axiosEnable.del=true;
|
||||||
|
}
|
||||||
|
else if(p=="role:add")
|
||||||
|
{
|
||||||
|
axiosEnable.add=true;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
break;
|
||||||
|
case "menu":
|
||||||
|
per.forEach(p => {
|
||||||
|
if(p=="menu:get")
|
||||||
|
{
|
||||||
|
axiosEnable.get=true;
|
||||||
|
}
|
||||||
|
else if(p=="menu:update")
|
||||||
|
{
|
||||||
|
axiosEnable.update=true;
|
||||||
|
}
|
||||||
|
else if(p=="menu:del")
|
||||||
|
{
|
||||||
|
axiosEnable.del=true;
|
||||||
|
}
|
||||||
|
else if(p=="menu:add")
|
||||||
|
{
|
||||||
|
axiosEnable.add=true;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
break;
|
||||||
|
|
||||||
|
|
||||||
|
default: console.log("未发现合法路由")
|
||||||
|
}
|
||||||
|
return axiosEnable;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
export {getBtn};
|
||||||
@@ -1,29 +1,26 @@
|
|||||||
export function setTreeMenu(menuList) {
|
export function toTree(data) {
|
||||||
if (menuList != null && menuList.length > 0) {
|
// 删除 所有 children,以防止多次调用
|
||||||
|
data.forEach(function (item) {
|
||||||
|
delete item.children;
|
||||||
|
});
|
||||||
|
|
||||||
//结果
|
// 将数据存储为 以 id 为 KEY 的 map 索引数据列
|
||||||
var res;
|
var map = {};
|
||||||
//获取最小的parentId
|
data.forEach(function (item) {
|
||||||
var minParentId = 0;
|
map[item.id] = item;
|
||||||
//获取id=最小的parentId的菜单列表
|
});
|
||||||
var menuList1=menuList.filter((item)=>{item.parentId==minParentId}) ;
|
// console.log(map);
|
||||||
|
var val = [];
|
||||||
menuList1.forEach(element=>{
|
data.forEach(function (item) {
|
||||||
res.push(element)
|
// 以当前遍历项,的pid,去map对象中找到索引的id
|
||||||
var children=menuList.filter((item)=>{item.parentId==element.id}) ;
|
var parent = map[item.parentId];
|
||||||
if (children.length > 0) {
|
// 好绕啊,如果找到索引,那么说明此项不在顶级当中,那么需要把此项添加到,他对应的父级中
|
||||||
setTreeChildren(menuList, children,element)
|
if (parent) {
|
||||||
}
|
(parent.children || ( parent.children = [] )).push(item);
|
||||||
})
|
} else {
|
||||||
}
|
//如果没有在map中找到对应的索引ID,那么直接把 当前的item添加到 val结果集中,作为顶级
|
||||||
}
|
val.push(item);
|
||||||
|
|
||||||
function setTreeChildren(menuList, childrenList,model) {
|
|
||||||
childrenList.forEach(element => {
|
|
||||||
model.Childs.push(element);
|
|
||||||
var childrenList2=menuList.filter((item)=>{item.parentId==element.id}) ;
|
|
||||||
if (childrenList2.length > 0) {
|
|
||||||
setTreeChildren(menuList, childrenList2,element)
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
return val;
|
||||||
}
|
}
|
||||||
@@ -31,14 +31,14 @@ myaxios.interceptors.request.use(function(config) {
|
|||||||
// 响应拦截器
|
// 响应拦截器
|
||||||
myaxios.interceptors.response.use(async function(response) {
|
myaxios.interceptors.response.use(async function(response) {
|
||||||
const resp = response.data
|
const resp = response.data
|
||||||
if (resp.code == undefined && resp.msg == undefined) {
|
if (resp.code == undefined && resp.message == undefined) {
|
||||||
vm.$dialog.notify.error("错误代码:无,原因:与服务器失去连接", {
|
vm.$dialog.notify.error("错误代码:无,原因:与服务器失去连接", {
|
||||||
position: "top-right",
|
position: "top-right",
|
||||||
timeout: 5000,
|
timeout: 5000,
|
||||||
});
|
});
|
||||||
} else if (resp.code == 401) {
|
} else if (resp.code == 401) {
|
||||||
const res = await vm.$dialog.error({
|
const res = await vm.$dialog.error({
|
||||||
text: `错误代码:${resp.code},原因:${resp.msg}<br>是否重新进行登录?`,
|
text: `错误代码:${resp.code},原因:${resp.message}<br>是否重新进行登录?`,
|
||||||
title: '错误',
|
title: '错误',
|
||||||
actions: {
|
actions: {
|
||||||
'false': '取消',
|
'false': '取消',
|
||||||
@@ -50,7 +50,7 @@ myaxios.interceptors.response.use(async function(response) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
} else if (resp.code !== 200) {
|
} else if (resp.code !== 200) {
|
||||||
vm.$dialog.notify.error(`错误代码:${resp.code},原因:${resp.msg}`, {
|
vm.$dialog.notify.error(`错误代码:${resp.code},原因:${resp.message}`, {
|
||||||
position: "top-right",
|
position: "top-right",
|
||||||
timeout: 5000,
|
timeout: 5000,
|
||||||
});
|
});
|
||||||
@@ -60,14 +60,14 @@ myaxios.interceptors.response.use(async function(response) {
|
|||||||
return resp;
|
return resp;
|
||||||
}, async function(error) {
|
}, async function(error) {
|
||||||
const resp = error.response.data
|
const resp = error.response.data
|
||||||
if (resp.code == undefined && resp.msg == undefined) {
|
if (resp.code == undefined && resp.message == undefined) {
|
||||||
vm.$dialog.notify.error("错误代码:无,原因:与服务器失去连接", {
|
vm.$dialog.notify.error("错误代码:无,原因:与服务器失去连接", {
|
||||||
position: "top-right",
|
position: "top-right",
|
||||||
timeout: 5000,
|
timeout: 5000,
|
||||||
});
|
});
|
||||||
} else if (resp.code == 401) {
|
} else if (resp.code == 401) {
|
||||||
const res = await vm.$dialog.error({
|
const res = await vm.$dialog.error({
|
||||||
text: `错误代码:${resp.code},原因:${resp.msg}<br>是否重新进行登录?`,
|
text: `错误代码:${resp.code},原因:${resp.message}<br>是否重新进行登录?`,
|
||||||
title: '错误',
|
title: '错误',
|
||||||
actions: {
|
actions: {
|
||||||
'false': '取消',
|
'false': '取消',
|
||||||
@@ -81,7 +81,7 @@ myaxios.interceptors.response.use(async function(response) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
} else if (resp.code !== 200) {
|
} else if (resp.code !== 200) {
|
||||||
vm.$dialog.notify.error(`错误代码:${resp.code},原因:${resp.msg}`, {
|
vm.$dialog.notify.error(`错误代码:${resp.code},原因:${resp.message}`, {
|
||||||
position: "top-right",
|
position: "top-right",
|
||||||
timeout: 5000,
|
timeout: 5000,
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -8,6 +8,11 @@ export function deepCopy(obj) {
|
|||||||
|
|
||||||
//转换数据,0是相等,1是模糊查询
|
//转换数据,0是相等,1是模糊查询
|
||||||
export function objctToDic(object, isByPage) {
|
export function objctToDic(object, isByPage) {
|
||||||
|
if (object == undefined) {
|
||||||
|
|
||||||
|
object = {};
|
||||||
|
}
|
||||||
|
|
||||||
if (isByPage) {
|
if (isByPage) {
|
||||||
var paramPage = {
|
var paramPage = {
|
||||||
"index": object.pageIndex,
|
"index": object.pageIndex,
|
||||||
@@ -20,7 +25,7 @@ export function objctToDic(object, isByPage) {
|
|||||||
delete newData.pageIndex;
|
delete newData.pageIndex;
|
||||||
delete newData.pageSize;
|
delete newData.pageSize;
|
||||||
|
|
||||||
var newList = [Object.keys(newData).map(val => {
|
var newList = [Object.keys(newData).map(val => {
|
||||||
return {
|
return {
|
||||||
key: val,
|
key: val,
|
||||||
value: object[val],
|
value: object[val],
|
||||||
@@ -30,11 +35,9 @@ export function objctToDic(object, isByPage) {
|
|||||||
|
|
||||||
//过滤封装
|
//过滤封装
|
||||||
newList[0].forEach((item, index) => {
|
newList[0].forEach((item, index) => {
|
||||||
if(item.value.length>0)
|
if (item.value.length > 0) {
|
||||||
{
|
if (item.key == 'isDeleted') {
|
||||||
if(item.key=='isDeleted')
|
item.type = 0;
|
||||||
{
|
|
||||||
item.type=0;
|
|
||||||
}
|
}
|
||||||
paramPage.parameters.push(item);
|
paramPage.parameters.push(item);
|
||||||
}
|
}
|
||||||
@@ -55,11 +58,9 @@ export function objctToDic(object, isByPage) {
|
|||||||
}
|
}
|
||||||
})]
|
})]
|
||||||
thisList[0].forEach((item, index) => {
|
thisList[0].forEach((item, index) => {
|
||||||
if(item.value.length>0)
|
if (item.value.length > 0) {
|
||||||
{
|
if (item.key == 'isDeleted') {
|
||||||
if(item.key=='isDeleted')
|
item.type = 0;
|
||||||
{
|
|
||||||
item.type=0;
|
|
||||||
}
|
}
|
||||||
params.parameters.push(item);
|
params.parameters.push(item);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,17 +7,20 @@
|
|||||||
:defaultItem="defaultItem"
|
:defaultItem="defaultItem"
|
||||||
:headers="headers"
|
:headers="headers"
|
||||||
:axiosUrls="axiosUrls"
|
:axiosUrls="axiosUrls"
|
||||||
|
:btnEnable="btnEnable"
|
||||||
>
|
>
|
||||||
</ccTable>
|
</ccTable>
|
||||||
</material-card>
|
</material-card>
|
||||||
</template>
|
</template>
|
||||||
<script>
|
<script>
|
||||||
|
import { getBtn } from "../util/btnHandle";
|
||||||
export default {
|
export default {
|
||||||
created() {
|
created() {
|
||||||
this.init();
|
this.init();
|
||||||
},
|
},
|
||||||
methods: {
|
methods: {
|
||||||
init() {
|
init() {
|
||||||
|
this.btnEnable = getBtn("role")
|
||||||
this.axiosUrls = {
|
this.axiosUrls = {
|
||||||
get: "/role/GetList",
|
get: "/role/GetList",
|
||||||
update: "/role/Update",
|
update: "/role/Update",
|
||||||
@@ -30,8 +33,10 @@ export default {
|
|||||||
start: true,
|
start: true,
|
||||||
axiosUrls: {
|
axiosUrls: {
|
||||||
},
|
},
|
||||||
|
btnEnable:{},
|
||||||
headers: [
|
headers: [
|
||||||
{ text: "编号", align: "start", value: "id" },
|
// { text: "编号", align: "start", value: "id" },
|
||||||
|
{ text: "角色编号", value: "roleCode", sortable: false },
|
||||||
{ text: "角色名", value: "roleName", sortable: false },
|
{ text: "角色名", value: "roleName", sortable: false },
|
||||||
// { text: "云盘地址", value: "file_path", sortable: false },
|
// { text: "云盘地址", value: "file_path", sortable: false },
|
||||||
// { text: "简介", value: "introduce", sortable: false },
|
// { text: "简介", value: "introduce", sortable: false },
|
||||||
|
|||||||
@@ -47,8 +47,14 @@
|
|||||||
hoverable
|
hoverable
|
||||||
item-text="menuName"
|
item-text="menuName"
|
||||||
>
|
>
|
||||||
|
<template v-slot:prepend="{ item }">
|
||||||
|
<v-icon>
|
||||||
|
{{ item.menuIcon }}
|
||||||
|
</v-icon>
|
||||||
|
</template>
|
||||||
<template v-slot:append="{ item }">
|
<template v-slot:append="{ item }">
|
||||||
<v-btn>权限:{{ item.permissionCode }}</v-btn>
|
<app-btn v-if="item.menuType==0">路由:{{ item.router }}</app-btn>
|
||||||
|
<app-btn v-if="item.menuType==1" color="secondary">权限:{{ item.permissionCode }}</app-btn>
|
||||||
</template>
|
</template>
|
||||||
</v-treeview>
|
</v-treeview>
|
||||||
</v-card></v-col
|
</v-card></v-col
|
||||||
|
|||||||
@@ -3,22 +3,13 @@
|
|||||||
<template #title>
|
<template #title>
|
||||||
用户管理 — <small class="text-body-1">用户可拥有多个角色</small>
|
用户管理 — <small class="text-body-1">用户可拥有多个角色</small>
|
||||||
</template>
|
</template>
|
||||||
<ccCombobox
|
<ccCombobox headers="设置角色" :items="roleItems" @select="getSelect" itemText="roleName">
|
||||||
headers="设置角色"
|
|
||||||
:items="roleItems"
|
|
||||||
@select="getSelect"
|
|
||||||
itemText="role_name"
|
|
||||||
>
|
|
||||||
<template v-slot:save>
|
<template v-slot:save>
|
||||||
<v-btn @click="setRole" color="blue darken-1" text> 保存</v-btn>
|
<v-btn @click="setRole" color="blue darken-1" text> 保存</v-btn>
|
||||||
</template>
|
</template>
|
||||||
</ccCombobox>
|
</ccCombobox>
|
||||||
<ccTable
|
<ccTable :defaultItem="defaultItem" :headers="headers" :axiosUrls="axiosUrls" :btnEnable="btnEnable"
|
||||||
:defaultItem="defaultItem"
|
@selected="getTableSelect">
|
||||||
:headers="headers"
|
|
||||||
:axiosUrls="axiosUrls"
|
|
||||||
@selected="getTableSelect"
|
|
||||||
>
|
|
||||||
<template v-slot:action="{ item }">
|
<template v-slot:action="{ item }">
|
||||||
<v-icon small class="mr-2" @click="showItem(item)"> mdi-eye </v-icon>
|
<v-icon small class="mr-2" @click="showItem(item)"> mdi-eye </v-icon>
|
||||||
</template>
|
</template>
|
||||||
@@ -27,6 +18,8 @@
|
|||||||
</template>
|
</template>
|
||||||
<script>
|
<script>
|
||||||
import userApi from "../api/userApi";
|
import userApi from "../api/userApi";
|
||||||
|
import roleApi from "../api/roleApi";
|
||||||
|
import { getBtn } from "../util/btnHandle";
|
||||||
export default {
|
export default {
|
||||||
created() {
|
created() {
|
||||||
this.init();
|
this.init();
|
||||||
@@ -59,9 +52,8 @@ export default {
|
|||||||
});
|
});
|
||||||
},
|
},
|
||||||
init() {
|
init() {
|
||||||
|
//这里可以遍历后台的菜单code,根据对应的菜单code来给axiosUrls的增删改查赋值即可
|
||||||
//这里可以遍历后台的菜单code,根据对应的菜单code来给axiosUrls的增删改查赋值即可
|
this.btnEnable = getBtn("user")
|
||||||
|
|
||||||
this.axiosUrls = {
|
this.axiosUrls = {
|
||||||
get: "/user/GetList",
|
get: "/user/GetList",
|
||||||
update: "/user/Update",
|
update: "/user/Update",
|
||||||
@@ -69,9 +61,9 @@ export default {
|
|||||||
add: "/user/Add",
|
add: "/user/Add",
|
||||||
};
|
};
|
||||||
|
|
||||||
// roleApi.getRole().then((resp) => {
|
roleApi.getList().then((resp) => {
|
||||||
// this.roleItems = resp.data;
|
this.roleItems = JSON.parse(JSON.stringify(resp.data));
|
||||||
// });
|
});
|
||||||
},
|
},
|
||||||
setRole() {
|
setRole() {
|
||||||
var userIds = [];
|
var userIds = [];
|
||||||
@@ -82,8 +74,8 @@ export default {
|
|||||||
this.select.forEach((item) => {
|
this.select.forEach((item) => {
|
||||||
roleIds.push(item.id);
|
roleIds.push(item.id);
|
||||||
});
|
});
|
||||||
userApi.SetRoleByUser(userIds, roleIds).then((resp) => {
|
userApi.GiveUserSetRole(userIds, roleIds).then((resp) => {
|
||||||
this.$dialog.notify.success(resp.msg, {
|
this.$dialog.notify.success(resp.message, {
|
||||||
position: "top-right",
|
position: "top-right",
|
||||||
timeout: 5000,
|
timeout: 5000,
|
||||||
});
|
});
|
||||||
@@ -98,13 +90,14 @@ export default {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
data: () => ({
|
data: () => ({
|
||||||
|
btnEnable: [],
|
||||||
TableSelect: [],
|
TableSelect: [],
|
||||||
select: [],
|
select: [],
|
||||||
roleItems: [],
|
roleItems: [],
|
||||||
axiosUrls: {},
|
axiosUrls: {},
|
||||||
headers: [
|
headers: [
|
||||||
{ text: "用户名", value: "userName", sortable: false },
|
{ text: "用户名", value: "userName", sortable: false },
|
||||||
{ text: "密码", value: "password", sortable: false },
|
|
||||||
{ text: "图标", value: "icon", sortable: false },
|
{ text: "图标", value: "icon", sortable: false },
|
||||||
{ text: "昵称", value: "nick", sortable: true },
|
{ text: "昵称", value: "nick", sortable: true },
|
||||||
{ text: "邮箱", value: "email", sortable: true },
|
{ text: "邮箱", value: "email", sortable: true },
|
||||||
|
|||||||
@@ -52,7 +52,16 @@
|
|||||||
<a href="javascript:void(0)" class="mt-1"> 忘记密码? </a>
|
<a href="javascript:void(0)" class="mt-1"> 忘记密码? </a>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<v-btn block color="primary" @click="login" class="mt-6" :loading="loader" :disabled="btn_dis"> 登录 </v-btn>
|
<v-btn
|
||||||
|
block
|
||||||
|
color="primary"
|
||||||
|
@click="login"
|
||||||
|
class="mt-6"
|
||||||
|
:loading="loader"
|
||||||
|
:disabled="btn_dis"
|
||||||
|
>
|
||||||
|
登录
|
||||||
|
</v-btn>
|
||||||
</v-form>
|
</v-form>
|
||||||
</v-card-text>
|
</v-card-text>
|
||||||
|
|
||||||
@@ -70,7 +79,7 @@
|
|||||||
</v-card-text>
|
</v-card-text>
|
||||||
|
|
||||||
<!-- social links -->
|
<!-- social links -->
|
||||||
<v-card-actions class="d-flex justify-center ">
|
<v-card-actions class="d-flex justify-center">
|
||||||
<v-btn v-for="link in socialLink" :key="link.icon" icon class="ms-1">
|
<v-btn v-for="link in socialLink" :key="link.icon" icon class="ms-1">
|
||||||
<v-icon :color="$vuetify.theme.dark ? link.colorInDark : link.color">
|
<v-icon :color="$vuetify.theme.dark ? link.colorInDark : link.color">
|
||||||
{{ link.icon }}
|
{{ link.icon }}
|
||||||
@@ -81,11 +90,11 @@
|
|||||||
</template>
|
</template>
|
||||||
<script>
|
<script>
|
||||||
export default {
|
export default {
|
||||||
created(){
|
created() {
|
||||||
this.enterSearch();
|
this.enterSearch();
|
||||||
},
|
},
|
||||||
data: () => ({
|
data: () => ({
|
||||||
btn_dis:false,
|
btn_dis: false,
|
||||||
loader: null,
|
loader: null,
|
||||||
socialLink: [
|
socialLink: [
|
||||||
{
|
{
|
||||||
@@ -122,8 +131,7 @@ export default {
|
|||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
methods: {
|
methods: {
|
||||||
enterSearch() {
|
enterSearch() {
|
||||||
|
|
||||||
document.onkeydown = (e) => {
|
document.onkeydown = (e) => {
|
||||||
//13表示回车键,baseURI是当前页面的地址,为了更严谨,也可以加别的,可以打印e看一下
|
//13表示回车键,baseURI是当前页面的地址,为了更严谨,也可以加别的,可以打印e看一下
|
||||||
if (e.keyCode === 13 && e.target.baseURI.match("/")) {
|
if (e.keyCode === 13 && e.target.baseURI.match("/")) {
|
||||||
@@ -133,20 +141,29 @@ export default {
|
|||||||
};
|
};
|
||||||
},
|
},
|
||||||
login() {
|
login() {
|
||||||
this.loader = true;
|
this.loader = true;
|
||||||
this.btn_dis=true;
|
this.btn_dis = true;
|
||||||
this.$store.dispatch("Login", this.form).then((resp) => {
|
this.$store
|
||||||
if (resp.status) {
|
.dispatch("Login", this.form)
|
||||||
this.$router.push("/");
|
.then((resp) => {
|
||||||
} else {
|
if (resp.status) {
|
||||||
this.loader=null;
|
|
||||||
this.btn_dis=false;
|
this.$router.push("/");
|
||||||
this.$dialog.notify.error(resp.msg, {
|
} else {
|
||||||
position: "top-right",
|
|
||||||
timeout: 5000,
|
this.loader = null;
|
||||||
});
|
this.btn_dis = false;
|
||||||
}
|
this.$dialog.notify.error(resp.message, {
|
||||||
});
|
position: "top-right",
|
||||||
|
timeout: 5000,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch((error) => {
|
||||||
|
|
||||||
|
this.loader = false;
|
||||||
|
this.btn_dis = false;
|
||||||
|
});
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -335,7 +335,7 @@ export default {
|
|||||||
this.editInfo = Object.assign({}, this.userInfo);
|
this.editInfo = Object.assign({}, this.userInfo);
|
||||||
this.roleInfo = resp.data.roles;
|
this.roleInfo = resp.data.roles;
|
||||||
this.menuInfo = resp.data.menus;
|
this.menuInfo = resp.data.menus;
|
||||||
this.$store.commit("SET_USER", this.userInfo);
|
this.$store.commit("SET_NEW_USER", this.userInfo);
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
choiceImg() {
|
choiceImg() {
|
||||||
|
|||||||
Reference in New Issue
Block a user