Compare commits
40 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f5d0e3c057 | |||
| a2cb96b9a7 | |||
| 07a6c2af8a | |||
| b092bbb817 | |||
| b25e6dc736 | |||
| 096f8485b4 | |||
| 0d077bea34 | |||
| 8568e7c406 | |||
| 8ce45c0de5 | |||
| bebcf559a1 | |||
| 43c9d3564b | |||
| b7ebad03d0 | |||
| a4f03cfbc1 | |||
| 67992af570 | |||
| 99d2ebcbe8 | |||
| 5174fc9ec0 | |||
| e49d007908 | |||
| 10b57594ac | |||
| 52cd22c4c6 | |||
| 28c53b71ce | |||
| e6dae7d1e2 | |||
| e7fe909fd0 | |||
| c592925096 | |||
| 38eda262d6 | |||
| 1c08c837e6 | |||
| b932f6f6a0 | |||
| 764a77456e | |||
| 4199736bc7 | |||
| cacb525b3a | |||
| ee9f6bacf3 | |||
| d3556cc058 | |||
| de76f5872a | |||
|
|
dda94fd572 | ||
|
|
2ae5fe03a5 | ||
| dc705768fe | |||
| cead939fe4 | |||
| 586f4c36a6 | |||
| 301d27e5ef | |||
|
|
36de53cbcc | ||
| f767752aa4 |
25
.dockerignore
Normal file
25
.dockerignore
Normal file
@ -0,0 +1,25 @@
|
||||
**/.dockerignore
|
||||
**/.env
|
||||
**/.git
|
||||
**/.gitignore
|
||||
**/.project
|
||||
**/.settings
|
||||
**/.toolstarget
|
||||
**/.vs
|
||||
**/.vscode
|
||||
**/.idea
|
||||
**/*.*proj.user
|
||||
**/*.dbmdl
|
||||
**/*.jfm
|
||||
**/azds.yaml
|
||||
**/bin
|
||||
**/charts
|
||||
**/docker-compose*
|
||||
**/Dockerfile*
|
||||
**/node_modules
|
||||
**/npm-debug.log
|
||||
**/obj
|
||||
**/secrets.dev.yaml
|
||||
**/values.dev.yaml
|
||||
LICENSE
|
||||
README.md
|
||||
25
.gitignore
vendored
25
.gitignore
vendored
@ -259,16 +259,31 @@ paket-files/
|
||||
# Python Tools for Visual Studio (PTVS)
|
||||
__pycache__/
|
||||
*.pyc
|
||||
/ZR.Admin.WebApi/appsettings.Development.json
|
||||
/CodeGenerate
|
||||
/ZR.Admin.WebApi/appsettings.Production.json
|
||||
/ZR.Admin.WebApi/wwwroot/uploads
|
||||
/ZR.Admin.WebApi/wwwroot/Generatecode
|
||||
/ZR.Admin.WebApi/wwwroot/export
|
||||
/ZR.Vue/src/views/business/Gendemo.vue
|
||||
/ZR.Admin.WebApi/Properties/launchSettings.json
|
||||
/ZR.Admin.WebApi/ZRAdmin.xml
|
||||
/ZR.Admin.WebApi/DataProtection
|
||||
/Quartz.NET.WindowsService
|
||||
/ZRAdmin-vue
|
||||
/ZRAdmin-vue/node_modules/
|
||||
/ZRAdmin-vue/.DS_Store
|
||||
/ZRAdmin-vue/dist/
|
||||
/ZRAdmin-vue/npm-debug.log*
|
||||
/ZRAdmin-vue/yarn-debug.log*
|
||||
/ZRAdmin-vue/yarn-error.log*
|
||||
/ZRAdmin-vue/**/*.log
|
||||
/ZRAdmin-vue/tests/**/coverage/
|
||||
/ZRAdmin-vue/tests/e2e/reports
|
||||
/ZRAdmin-vue/selenium-debug.log
|
||||
/ZRAdmin-vue/.idea
|
||||
/ZRAdmin-vue/*.suo
|
||||
/ZRAdmin-vue/*.ntvs*
|
||||
/ZRAdmin-vue/*.njsproj
|
||||
/ZRAdmin-vue/*.sln
|
||||
/ZRAdmin-vue/*.local
|
||||
/ZRAdmin-vue/package-lock.json
|
||||
/ZRAdmin-vue/deploy.js
|
||||
/ZR.Admin.WebApi/ZRModel.xml
|
||||
ZRAdmin-vue/dist.zip
|
||||
**/.vshistory/
|
||||
@ -1,7 +1,7 @@
|
||||
using CSRedis;
|
||||
using Infrastructure;
|
||||
|
||||
namespace ZR.Common.Cache
|
||||
namespace ZR.Infrastructure.Cache
|
||||
{
|
||||
public class RedisServer
|
||||
{
|
||||
@ -12,6 +12,7 @@ namespace ZR.Common.Cache
|
||||
{
|
||||
Cache = new CSRedisClient(AppSettings.GetConfig("RedisServer:Cache"));
|
||||
Session = new CSRedisClient(AppSettings.GetConfig("RedisServer:Session"));
|
||||
RedisHelper.Initialization(Session);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
8
Infrastructure/Constant/SysNoticeLogStatus.cs
Normal file
8
Infrastructure/Constant/SysNoticeLogStatus.cs
Normal file
@ -0,0 +1,8 @@
|
||||
namespace ZR.Infrastructure.Constant;
|
||||
|
||||
public class SysNoticeLogStatus
|
||||
{
|
||||
public const string Unread = "0";
|
||||
|
||||
public const string Read = "1";
|
||||
}
|
||||
@ -194,6 +194,9 @@ namespace Infrastructure.Controllers
|
||||
if (!Directory.Exists(fullPath))
|
||||
{
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(fullPath));
|
||||
}
|
||||
if (!Path.Exists(fullPath))
|
||||
{
|
||||
MiniExcel.SaveAs(fullPath, list, overwriteFile: true);
|
||||
}
|
||||
return (sFileName, fullPath);
|
||||
|
||||
@ -170,7 +170,7 @@ namespace Infrastructure.Extensions
|
||||
{
|
||||
try
|
||||
{
|
||||
return bool.Parse(str.ToString());
|
||||
return bool.Parse(str.ToString() ?? string.Empty);
|
||||
}
|
||||
catch
|
||||
{
|
||||
@ -284,6 +284,9 @@ namespace Infrastructure.Extensions
|
||||
return DateTime.ParseExact(str, "yyyyMMddHH", System.Globalization.CultureInfo.CurrentCulture);
|
||||
case 12:
|
||||
return DateTime.ParseExact(str, "yyyyMMddHHmm", System.Globalization.CultureInfo.CurrentCulture);
|
||||
case 13:
|
||||
return DateTime.ParseExact(str, "yyyy.MM.dd ddd",
|
||||
System.Globalization.CultureInfo.CurrentCulture);
|
||||
case 14:
|
||||
return DateTime.ParseExact(str, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);
|
||||
default:
|
||||
|
||||
@ -157,7 +157,8 @@ namespace Infrastructure
|
||||
{
|
||||
new Claim(ClaimTypes.PrimarySid, user.UserId.ToString()),
|
||||
new Claim(ClaimTypes.Name, user.UserName),
|
||||
new Claim(ClaimTypes.UserData, JsonConvert.SerializeObject(user))
|
||||
new Claim(ClaimTypes.UserData, JsonConvert.SerializeObject(user)),
|
||||
new Claim("NickName", user.NickName)
|
||||
};
|
||||
|
||||
return claims;
|
||||
|
||||
@ -12,9 +12,9 @@ namespace Infrastructure.Model
|
||||
/// <summary>
|
||||
/// 主题
|
||||
/// </summary>
|
||||
[Required(ErrorMessage = "主题不能为空")]
|
||||
// [Required(ErrorMessage = "主题不能为空")]
|
||||
public string Subject { get; set; }
|
||||
[Required(ErrorMessage = "发送人不能为空")]
|
||||
// [Required(ErrorMessage = "发送人不能为空")]
|
||||
public string ToUser { get; set; }
|
||||
public string Content { get; set; } = "";
|
||||
public string HtmlContent { get; set; }
|
||||
|
||||
@ -9,6 +9,7 @@ namespace Infrastructure.Model
|
||||
public long UserId { get; set; }
|
||||
public long DeptId { get; set; }
|
||||
public string UserName { get; set; }
|
||||
public string NickName { get; set; }
|
||||
/// <summary>
|
||||
/// 角色集合
|
||||
/// </summary>
|
||||
@ -33,6 +34,7 @@ namespace Infrastructure.Model
|
||||
{
|
||||
UserId = info.UserId;
|
||||
UserName = info.UserName;
|
||||
NickName = info.NickName;
|
||||
DeptId = info.DeptId;
|
||||
Roles = roles;
|
||||
RoleIds = roles.Select(f => f.RoleKey).ToList();
|
||||
|
||||
59
Infrastructure/Resolver/AntPathMatcher.cs
Normal file
59
Infrastructure/Resolver/AntPathMatcher.cs
Normal file
@ -0,0 +1,59 @@
|
||||
using System;
|
||||
|
||||
namespace ZR.Infrastructure.Resolver;
|
||||
|
||||
public static class AntPathMatcher
|
||||
{
|
||||
public static bool Match(string pattern, string value)
|
||||
{
|
||||
if (pattern == null || value == null)
|
||||
return false;
|
||||
|
||||
if (pattern == "**")
|
||||
return true;
|
||||
|
||||
var patternSegments = pattern.Split('/');
|
||||
var valueSegments = value.Split('/');
|
||||
|
||||
int patternIndex = 0;
|
||||
int valueIndex = 0;
|
||||
int patternWildcardIndex = -1;
|
||||
int valueWildcardIndex = -1;
|
||||
|
||||
while (valueIndex < valueSegments.Length)
|
||||
{
|
||||
if (patternIndex < patternSegments.Length && IsMatch(patternSegments[patternIndex], valueSegments[valueIndex]))
|
||||
{
|
||||
patternIndex++;
|
||||
valueIndex++;
|
||||
}
|
||||
else if (patternWildcardIndex != -1)
|
||||
{
|
||||
patternIndex = patternWildcardIndex + 1;
|
||||
valueIndex = ++valueWildcardIndex;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
while (patternIndex < patternSegments.Length && patternSegments[patternIndex] == "**")
|
||||
{
|
||||
patternIndex++;
|
||||
}
|
||||
|
||||
return patternIndex >= patternSegments.Length && valueIndex >= valueSegments.Length;
|
||||
}
|
||||
|
||||
private static bool IsMatch(string patternSegment, string valueSegment)
|
||||
{
|
||||
if (patternSegment == "*")
|
||||
return true;
|
||||
|
||||
if (patternSegment.StartsWith("{") && patternSegment.EndsWith("}"))
|
||||
return true; // 支持占位符的匹配逻辑
|
||||
|
||||
return string.Equals(patternSegment, valueSegment, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
}
|
||||
42
Infrastructure/Resolver/JsonPropertyContractResolver.cs
Normal file
42
Infrastructure/Resolver/JsonPropertyContractResolver.cs
Normal file
@ -0,0 +1,42 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using Newtonsoft.Json.Serialization;
|
||||
|
||||
namespace ZR.Infrastructure.Resolver;
|
||||
|
||||
public class JsonPropertyContractResolver : CamelCasePropertyNamesContractResolver
|
||||
{
|
||||
private HashSet<string> _propertySet;
|
||||
|
||||
public JsonPropertyContractResolver(IEnumerable<string> propertyNames)
|
||||
{
|
||||
if (propertyNames != null)
|
||||
{
|
||||
_propertySet = new HashSet<string>(propertyNames, StringComparer.Ordinal);
|
||||
}
|
||||
}
|
||||
|
||||
// protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
|
||||
// {
|
||||
// var list = base.CreateProperties(type, memberSerialization).ToList();
|
||||
// var resList = list
|
||||
// .Where(a => !this._lstInclude.Contains(a.PropertyName))
|
||||
// .ToList();
|
||||
// return resList;
|
||||
// // .FindAll(p => _lstInclude.Contains(p.PropertyName));
|
||||
// }
|
||||
|
||||
protected override List<MemberInfo> GetSerializableMembers(Type objectType)
|
||||
{
|
||||
List<MemberInfo> serializableMembers = null;
|
||||
var allMembers = base.GetSerializableMembers(objectType);
|
||||
|
||||
if (_propertySet != null && _propertySet.Count > 0)
|
||||
{
|
||||
serializableMembers = allMembers.Where(m => !_propertySet.Contains(m.Name)).ToList();
|
||||
}
|
||||
return serializableMembers != null && serializableMembers.Count > 0 ? serializableMembers : allMembers;
|
||||
}
|
||||
}
|
||||
44
Infrastructure/Resolver/PropertyFilterContractResolver.cs
Normal file
44
Infrastructure/Resolver/PropertyFilterContractResolver.cs
Normal file
@ -0,0 +1,44 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Serialization;
|
||||
|
||||
namespace ZR.Infrastructure.Resolver;
|
||||
|
||||
public class PropertyFilterContractResolver : CamelCasePropertyNamesContractResolver
|
||||
{
|
||||
private readonly HashSet<string> _includedPaths;
|
||||
private readonly HashSet<string> _excludedPaths;
|
||||
|
||||
public PropertyFilterContractResolver(IEnumerable<string> includedPaths, IEnumerable<string> excludedPaths)
|
||||
{
|
||||
_includedPaths = includedPaths.ToHashSet();
|
||||
_excludedPaths = excludedPaths.ToHashSet();
|
||||
}
|
||||
|
||||
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
|
||||
{
|
||||
var properties = base.CreateProperties(type, memberSerialization);
|
||||
|
||||
properties = properties.Where(p => IsIncluded(p) && !IsExcluded(p)).ToList();
|
||||
|
||||
return properties;
|
||||
}
|
||||
|
||||
private bool IsIncluded(JsonProperty property)
|
||||
{
|
||||
if (_includedPaths == null || _includedPaths.Count == 0)
|
||||
return true;
|
||||
|
||||
return _includedPaths.Any(path => AntPathMatcher.Match(path, property.PropertyName));
|
||||
}
|
||||
|
||||
private bool IsExcluded(JsonProperty property)
|
||||
{
|
||||
if (_excludedPaths == null || _excludedPaths.Count == 0)
|
||||
return false;
|
||||
|
||||
return _excludedPaths.Any(path => AntPathMatcher.Match(path, property.PropertyName));
|
||||
}
|
||||
}
|
||||
@ -16,8 +16,10 @@ namespace Infrastructure
|
||||
|
||||
types.GetProperty("CreateTime", flag)?.SetValue(source, DateTime.Now, null);
|
||||
types.GetProperty("AddTime", flag)?.SetValue(source, DateTime.Now, null);
|
||||
types.GetProperty("CreateBy", flag)?.SetValue(source, context.GetName(), null);
|
||||
types.GetProperty("Create_by", flag)?.SetValue(source, context.GetName(), null);
|
||||
types.GetProperty("CreateBy", flag)?.SetValue(source, context.GetUId(), null);
|
||||
types.GetProperty("CreateName", flag)?.SetValue(source, context.GetNickName(), null);
|
||||
types.GetProperty("Create_by", flag)?.SetValue(source, context.GetUId(), null);
|
||||
types.GetProperty("Create_name", flag)?.SetValue(source, context.GetNickName(), null);
|
||||
types.GetProperty("UserId", flag)?.SetValue(source, context.GetUId(), null);
|
||||
|
||||
return source;
|
||||
@ -31,9 +33,10 @@ namespace Infrastructure
|
||||
|
||||
types.GetProperty("UpdateTime", flag)?.SetValue(source, DateTime.Now, null);
|
||||
types.GetProperty("Update_time", flag)?.SetValue(source, DateTime.Now, null);
|
||||
types.GetProperty("UpdateBy", flag)?.SetValue(source, context.GetName(), null);
|
||||
types.GetProperty("Update_by", flag)?.SetValue(source, context.GetName(), null);
|
||||
|
||||
types.GetProperty("UpdateBy", flag)?.SetValue(source, context.GetUId(), null);
|
||||
types.GetProperty("Update_by", flag)?.SetValue(source, context.GetUId(), null);
|
||||
types.GetProperty("UpdateName", flag)?.SetValue(source, context.GetNickName(), null);
|
||||
types.GetProperty("Update_name", flag)?.SetValue(source, context.GetNickName(), null);
|
||||
return source;
|
||||
}
|
||||
|
||||
|
||||
@ -91,6 +91,14 @@ namespace Infrastructure.Extensions
|
||||
|
||||
return uid;
|
||||
}
|
||||
|
||||
public static string? GetNickName(this HttpContext context)
|
||||
{
|
||||
var nickName = context.User.FindFirstValue("NickName");
|
||||
if (string.IsNullOrEmpty(nickName))
|
||||
nickName = null;
|
||||
return nickName;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 判断是否是管理员
|
||||
|
||||
@ -17,8 +17,8 @@ namespace ZR.Infrastructure.WebExtensions
|
||||
//从appsettings.json中加载Ip规则
|
||||
services.Configure<IpRateLimitPolicies>(configuration.GetSection("IpRateLimitPolicies"));
|
||||
//注入计数器和规则存储
|
||||
services.AddSingleton<IIpPolicyStore, MemoryCacheIpPolicyStore>();
|
||||
services.AddSingleton<IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>();
|
||||
services.AddSingleton<IIpPolicyStore, DistributedCacheIpPolicyStore>();
|
||||
services.AddSingleton<IRateLimitCounterStore, DistributedCacheRateLimitCounterStore>();
|
||||
//配置(解析器、计数器密钥生成器)
|
||||
services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();
|
||||
services.AddSingleton<IProcessingStrategy, AsyncKeyLockProcessingStrategy>();
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net7.0</TargetFramework>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
|
||||
<NoWarn>8632</NoWarn>
|
||||
@ -12,8 +12,13 @@
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AspectCore.Abstractions" Version="2.4.0" />
|
||||
<PackageReference Include="Caching.CSRedis" Version="3.8.670" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.SignalR.Client" Version="7.0.12" />
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyModel" Version="7.0.0" />
|
||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
|
||||
<PackageReference Include="RulesEngine" Version="5.0.2" />
|
||||
<PackageReference Include="SqlSugar.IOC" Version="2.0.0" />
|
||||
<PackageReference Include="SqlSugarCoreNoDrive" Version="5.1.4.109" />
|
||||
<PackageReference Include="UAParser" Version="3.1.47" />
|
||||
<PackageReference Include="IPTools.China" Version="1.6.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="7.0.7" />
|
||||
|
||||
@ -1,11 +1,11 @@
|
||||
<h2 align="center"> ZR.Admin.NET Back-end management system</h2>
|
||||
<h4 align="center">base.NET5/.Net7 + vue2.x/vue3.x/uniapp Front-end and back-end separation of .NET rapid development framework</h4>
|
||||
<h4 align="center">base .Net7 + vue2.x/vue3.x/uniapp Front-end and back-end separation of .NET rapid development framework</h4>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://gitee.com/izory/ZrAdminNetCore"><img src="https://gitee.com/izory/ZrAdminNetCore/badge/star.svg?theme=dark"></a>
|
||||
<a href='https://gitee.com/izory/ZrAdminNetCore/members'><img src='https://gitee.com/izory/ZrAdminNetCore/badge/fork.svg?theme=dark' alt='fork'></img></a>
|
||||
<a href="https://gitee.com/izory/ZrAdminNetCore/blob/master/LICENSE"><img src="https://img.shields.io/github/license/mashape/apistatus.svg"></a>
|
||||
<a href="http://www.izhaorui.cn/doc/changelog.html"><img src="https://img.shields.io/badge/更新日志-20230713-yellow"/></a>
|
||||
<a href="http://www.izhaorui.cn/doc/changelog.html"><img src="https://img.shields.io/badge/更新日志-20230920-yellow"/></a>
|
||||
</p>
|
||||
|
||||
---
|
||||
|
||||
30
README.md
30
README.md
@ -1,11 +1,11 @@
|
||||
<h2 align="center"> ZR.Admin.NET后台管理系统</h2>
|
||||
<h4 align="center">基于.NET5/.Net7 + vue2.x/vue3.x/uniapp前后端分离的.net快速开发框架</h4>
|
||||
<h4 align="center">基于.Net7 + vue2.x/vue3.x/uniapp前后端分离的.net快速开发框架</h4>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://gitee.com/izory/ZrAdminNetCore"><img src="https://gitee.com/izory/ZrAdminNetCore/badge/star.svg?theme=dark"></a>
|
||||
<a href='https://gitee.com/izory/ZrAdminNetCore/members'><img src='https://gitee.com/izory/ZrAdminNetCore/badge/fork.svg?theme=dark' alt='fork'></img></a>
|
||||
<a href="https://gitee.com/izory/ZrAdminNetCore/blob/master/LICENSE"><img src="https://img.shields.io/github/license/mashape/apistatus.svg"></a>
|
||||
<a href="http://www.izhaorui.cn/doc/changelog.html"><img src="https://img.shields.io/badge/更新日志-20230811-yellow"/></a>
|
||||
<a href="http://www.izhaorui.cn/doc/changelog.html"><img src="https://img.shields.io/badge/更新日志-20230920-yellow"/></a>
|
||||
</p>
|
||||
|
||||
---
|
||||
@ -50,10 +50,10 @@
|
||||
|
||||
## 💒 代码仓库
|
||||
|
||||
| 仓库 | Github | Gitee |
|
||||
| -------------- | ------------------------------------------------------ | ---------------------------------------------------------------- |
|
||||
| 仓库 | Github | Gitee |
|
||||
| -------------- | ------------------------------------------------------ | --------------------------------------------------- |
|
||||
| Net7 | [克隆/下载](https://github.com/izhaorui/Zr.Admin.NET) | [克隆/下载](https://gitee.com/izory/ZrAdminNetCore) |
|
||||
| Vue3(推荐使用) | [克隆/下载](https://github.com/izhaorui/ZR.Admin.Vue3) | [克隆/下载](https://gitee.com/izory/ZRAdmin-vue) |
|
||||
| Vue3(推荐使用) | [克隆/下载](https://github.com/izhaorui/ZR.Admin.Vue3) | [克隆/下载](https://gitee.com/izory/ZRAdmin-vue) |
|
||||
|
||||
## 🍁 前端技术
|
||||
|
||||
@ -72,7 +72,7 @@ Vue 版前端技术栈 :基于 vue2.x/vue3.x/uniapp、vuex、vue-router 、vue
|
||||
- 分库分表:使用 orm sqlsugar 可以很轻松的实现分库分库性能优越
|
||||
- 多 租 户:支持多租户功能
|
||||
- 缓存数据:内置内存缓存和 Redis
|
||||
- signalR:使用signalr管理用户在线状态
|
||||
- signalR:使用 signalr 管理用户在线状态
|
||||
|
||||
## 🍖 内置功能
|
||||
|
||||
@ -105,13 +105,13 @@ Vue 版前端技术栈 :基于 vue2.x/vue3.x/uniapp、vuex、vue-router 、vue
|
||||

|
||||
|
||||
```
|
||||
├─ZR.Service ->[你的业务服务层类库]:提供WebApi接口调用;
|
||||
├─ZR.ServiceCore ->[系统服务层类库]:提供WebApi接口调用;
|
||||
├─ZR.Repository ->[仓库层类库]:方便提供有执行存储过程的操作;
|
||||
├─ZR.Model ->[实体层类库]:提供项目中的数据库表、数据传输对象;
|
||||
├─ZR.Admin.WebApi ->[webapi接口]:为Vue版或其他三方系统提供接口服务。
|
||||
├─ZR.Service ->[你的业务服务层类库]:提供WebApi接口调用;
|
||||
├─ZR.ServiceCore ->[系统服务层类库]:提供WebApi接口调用;
|
||||
├─ZR.Repository ->[仓库层类库]:方便提供有执行存储过程的操作;
|
||||
├─ZR.Model ->[实体层类库]:提供项目中的数据库表、数据传输对象;
|
||||
├─ZR.Admin.WebApi ->[webapi接口]:为Vue版或其他三方系统提供接口服务。
|
||||
├─ZR.Tasks ->[定时任务类库]:提供项目定时任务实现功能;
|
||||
├─ZR.CodeGenerator ->[代码生成功能]:包含代码生成的模板、方法、代码生成的下载。
|
||||
├─ZR.CodeGenerator ->[代码生成功能]:包含代码生成的模板、方法、代码生成的下载。
|
||||
├─ZR.Vue ->[前端UI]:vue2.0版本UI层(已经不再更新推荐使用vue3)。
|
||||
├─document ->[文档]:数据库脚本
|
||||
```
|
||||
@ -153,12 +153,15 @@ Vue 版前端技术栈 :基于 vue2.x/vue3.x/uniapp、vuex、vue-router 、vue
|
||||
</tr>
|
||||
<tr>
|
||||
<td><img src="https://gitee.com/izory/ZrAdminNetCore/raw/master/document/images/17.png"/></td>
|
||||
<td><img src="https://gitee.com/izory/ZrAdminNetCore/raw/master/document/images/18.png"/></td>
|
||||
<td><img src="https://gitee.com/izory/ZrAdminNetCore/raw/master/document/images/18.png"/></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><img src="https://gitee.com/izory/ZrAdminNetCore/raw/master/document/images/19.png"/></td>
|
||||
<td><img src="https://gitee.com/izory/ZrAdminNetCore/raw/master/document/images/20.png"/></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><img src="https://gitee.com/izory/ZrAdminNetCore/raw/master/document/images/21.png"/></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
## 移动端演示图
|
||||
@ -195,6 +198,7 @@ Vue 版前端技术栈 :基于 vue2.x/vue3.x/uniapp、vuex、vue-router 、vue
|
||||
5. 自定义的代码生成功能
|
||||
6. 依赖少,上手容易
|
||||
7. 文档全面
|
||||
8. 支持中文表头导入数据
|
||||
|
||||
## 💐 特别鸣谢
|
||||
|
||||
|
||||
17
ZR.Admin.Grpc/Extensions/GrpcServiceExtensions.cs
Normal file
17
ZR.Admin.Grpc/Extensions/GrpcServiceExtensions.cs
Normal file
@ -0,0 +1,17 @@
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace ZR.Admin.Grpc.Extensions;
|
||||
|
||||
public static class GrpcServiceExtensions
|
||||
{
|
||||
public static void AddGrpcServiceConfiguration(this IServiceCollection services, IConfiguration configuration)
|
||||
{
|
||||
// services.AddTransient<AuthUn>()
|
||||
|
||||
services.AddGrpcClient<Greeter.GreeterClient>(options =>
|
||||
{
|
||||
options.Address = new Uri(configuration.GetValue<string>("GrpcUrls:FindTeacher"));
|
||||
});
|
||||
}
|
||||
}
|
||||
54
ZR.Admin.Grpc/Protos/FileTransfer.proto
Normal file
54
ZR.Admin.Grpc/Protos/FileTransfer.proto
Normal file
@ -0,0 +1,54 @@
|
||||
syntax = "proto3";
|
||||
|
||||
option csharp_namespace = "ZR.Admin.Grpc";
|
||||
|
||||
package filetransfer;
|
||||
|
||||
service FileTransfer {
|
||||
rpc InitUpload (InitUploadRequest) returns (InitUploadResponse);
|
||||
rpc UploadChunk (stream UploadChunkRequest) returns (UploadChunkResponse);
|
||||
rpc CompleteUpload (CompleteUploadRequest) returns (CompleteUploadResponse);
|
||||
rpc CheckUploadStatus (CheckUploadStatusRequest) returns (CheckUploadStatusResponse);
|
||||
}
|
||||
|
||||
message InitUploadRequest {
|
||||
string file_name = 1;
|
||||
int64 file_size = 2;
|
||||
string file_hash = 3;
|
||||
}
|
||||
|
||||
message InitUploadResponse {
|
||||
string session_id = 1;
|
||||
int64 uploaded_bytes = 2;
|
||||
}
|
||||
|
||||
message UploadChunkRequest {
|
||||
string session_id = 1;
|
||||
bytes chunk_data = 2;
|
||||
int64 offset = 3;
|
||||
}
|
||||
|
||||
message UploadChunkResponse {
|
||||
int64 uploaded_bytes = 1;
|
||||
}
|
||||
|
||||
message CompleteUploadRequest {
|
||||
string session_id = 1;
|
||||
string file_hash = 2;
|
||||
}
|
||||
|
||||
message CompleteUploadResponse {
|
||||
bool success = 1;
|
||||
string message = 2;
|
||||
}
|
||||
|
||||
message CheckUploadStatusRequest {
|
||||
string file_name = 1;
|
||||
string file_hash = 2;
|
||||
}
|
||||
|
||||
message CheckUploadStatusResponse {
|
||||
string session_id = 1;
|
||||
int64 uploaded_bytes = 2;
|
||||
bool exists = 3;
|
||||
}
|
||||
17
ZR.Admin.Grpc/Protos/block.proto
Normal file
17
ZR.Admin.Grpc/Protos/block.proto
Normal file
@ -0,0 +1,17 @@
|
||||
syntax = "proto3";
|
||||
|
||||
option csharp_namespace = "GrpcService1";
|
||||
|
||||
package block;
|
||||
|
||||
service Block {
|
||||
rpc GetBlock (BlockRequest) returns (BlockReply);
|
||||
}
|
||||
|
||||
message BlockRequest {
|
||||
string in = 1;
|
||||
}
|
||||
|
||||
message BlockReply {
|
||||
string out = 1;
|
||||
}
|
||||
21
ZR.Admin.Grpc/Protos/greet.proto
Normal file
21
ZR.Admin.Grpc/Protos/greet.proto
Normal file
@ -0,0 +1,21 @@
|
||||
syntax = "proto3";
|
||||
|
||||
option csharp_namespace = "ZR.Admin.Grpc";
|
||||
|
||||
package greet;
|
||||
|
||||
// The greeting service definition.
|
||||
service Greeter {
|
||||
// Sends a greeting
|
||||
rpc SayHello (HelloRequest) returns (HelloReply);
|
||||
}
|
||||
|
||||
// The request message containing the user's name.
|
||||
message HelloRequest {
|
||||
string name = 1;
|
||||
}
|
||||
|
||||
// The response message containing the greetings.
|
||||
message HelloReply {
|
||||
string message = 1;
|
||||
}
|
||||
35
ZR.Admin.Grpc/Protos/my_diary.proto
Normal file
35
ZR.Admin.Grpc/Protos/my_diary.proto
Normal file
@ -0,0 +1,35 @@
|
||||
syntax = "proto3";
|
||||
|
||||
option csharp_namespace = "ZR.Admin.Grpc";
|
||||
|
||||
package my.diary;
|
||||
|
||||
import "google/protobuf/timestamp.proto";
|
||||
|
||||
// The greeting service definition.
|
||||
service MyDiary {
|
||||
// Sends a greeting
|
||||
rpc Edit (EditRequest) returns (EditReply);
|
||||
rpc Query (QueryRequest) returns (QueryReply);
|
||||
}
|
||||
|
||||
// The request message containing the user's name.
|
||||
message EditRequest {
|
||||
string content = 1;
|
||||
int64 user_id = 2;
|
||||
google.protobuf.Timestamp create_time = 3; // 字段名仍然建议使用 snake_case
|
||||
}
|
||||
|
||||
// The response message containing the greetings.
|
||||
message EditReply {
|
||||
string result_message = 1;
|
||||
}
|
||||
|
||||
message QueryRequest {
|
||||
int64 user_id = 1;
|
||||
google.protobuf.Timestamp create_time = 2;
|
||||
}
|
||||
|
||||
message QueryReply {
|
||||
string content = 1;
|
||||
}
|
||||
109
ZR.Admin.Grpc/Services/FileTransferService.cs
Normal file
109
ZR.Admin.Grpc/Services/FileTransferService.cs
Normal file
@ -0,0 +1,109 @@
|
||||
using Grpc.Core;
|
||||
using ZR.Admin.Grpc;
|
||||
|
||||
namespace GrpcService.Services
|
||||
{
|
||||
public class FileTransferService : FileTransfer.FileTransferBase
|
||||
{
|
||||
private readonly string _storagePath = "Îļþ";
|
||||
private readonly IUploadSessionManager _sessionManager;
|
||||
|
||||
public FileTransferService(IUploadSessionManager sessionManager)
|
||||
{
|
||||
Directory.CreateDirectory(_storagePath);
|
||||
_sessionManager = sessionManager;
|
||||
}
|
||||
|
||||
public override Task<InitUploadResponse> InitUpload(InitUploadRequest request, ServerCallContext context)
|
||||
{
|
||||
var sessionId = _sessionManager.CreateSession(request.FileName, request.FileSize, request.FileHash);
|
||||
var uploadedBytes = _sessionManager.GetUploadedBytes(sessionId);
|
||||
|
||||
return Task.FromResult(new InitUploadResponse
|
||||
{
|
||||
SessionId = sessionId,
|
||||
UploadedBytes = uploadedBytes
|
||||
});
|
||||
}
|
||||
|
||||
public override async Task<UploadChunkResponse> UploadChunk(IAsyncStreamReader<UploadChunkRequest> requestStream, ServerCallContext context)
|
||||
{
|
||||
UploadChunkRequest currentRequest = null;
|
||||
var response = new UploadChunkResponse();
|
||||
|
||||
while (await requestStream.MoveNext())
|
||||
{
|
||||
currentRequest = requestStream.Current;
|
||||
var session = _sessionManager.GetSession(currentRequest.SessionId);
|
||||
|
||||
if (session == null)
|
||||
{
|
||||
throw new RpcException(new Status(StatusCode.NotFound, "Session not found"));
|
||||
}
|
||||
|
||||
using (var fileStream = new FileStream(session.TempFilePath, FileMode.OpenOrCreate, FileAccess.Write))
|
||||
{
|
||||
fileStream.Seek(currentRequest.Offset, SeekOrigin.Begin);
|
||||
await fileStream.WriteAsync(currentRequest.ChunkData.ToByteArray(), 0, currentRequest.ChunkData.Length);
|
||||
}
|
||||
|
||||
_sessionManager.UpdateSessionProgress(currentRequest.SessionId, currentRequest.Offset + currentRequest.ChunkData.Length);
|
||||
response.UploadedBytes = currentRequest.Offset + currentRequest.ChunkData.Length;
|
||||
}
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
public override async Task<CompleteUploadResponse> CompleteUpload(CompleteUploadRequest request, ServerCallContext context)
|
||||
{
|
||||
var session = _sessionManager.GetSession(request.SessionId);
|
||||
if (session == null)
|
||||
{
|
||||
return await Task.FromResult(new CompleteUploadResponse
|
||||
{
|
||||
Success = false,
|
||||
Message = "Session not found"
|
||||
});
|
||||
}
|
||||
|
||||
// Verify file hash if needed
|
||||
if (!string.IsNullOrEmpty(request.FileHash))
|
||||
{
|
||||
var actualHash = await FileHelper.GetQuickFileIdentity(session.TempFilePath);
|
||||
if (actualHash != request.FileHash)
|
||||
{
|
||||
return await Task.FromResult(new CompleteUploadResponse
|
||||
{
|
||||
Success = false,
|
||||
Message = "File hash mismatch"
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Move temp file to final location
|
||||
var finalPath = Path.Combine(_storagePath, session.FileName);
|
||||
//var finalPath = FileHelper.GetUniqueFilePath(_storagePath, session.FileName);
|
||||
File.Move(session.TempFilePath, finalPath, true);
|
||||
|
||||
_sessionManager.CompleteSession(request.SessionId);
|
||||
|
||||
return await Task.FromResult(new CompleteUploadResponse
|
||||
{
|
||||
Success = true,
|
||||
Message = "File uploaded successfully"
|
||||
});
|
||||
}
|
||||
|
||||
public override Task<CheckUploadStatusResponse> CheckUploadStatus(CheckUploadStatusRequest request, ServerCallContext context)
|
||||
{
|
||||
var session = _sessionManager.FindSession(request.FileName, request.FileHash);
|
||||
|
||||
return Task.FromResult(new CheckUploadStatusResponse
|
||||
{
|
||||
SessionId = session?.SessionId ?? "",
|
||||
UploadedBytes = session?.UploadedBytes ?? 0,
|
||||
Exists = session != null
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
37
ZR.Admin.Grpc/Services/GreeterService.cs
Normal file
37
ZR.Admin.Grpc/Services/GreeterService.cs
Normal file
@ -0,0 +1,37 @@
|
||||
using Grpc.Core;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ZR.Admin.Grpc.Services
|
||||
{
|
||||
public class GreeterService : Greeter.GreeterBase
|
||||
{
|
||||
private readonly ILogger<GreeterService> _logger;
|
||||
|
||||
public GreeterService(ILogger<GreeterService> logger)
|
||||
{
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
// 实现 SayHello 方法
|
||||
// 第一个参数是请求消息 (HelloRequest)
|
||||
// 第二个参数是服务器上下文 (ServerCallContext),提供关于当前调用的信息
|
||||
public override Task<HelloReply> SayHello(HelloRequest request, ServerCallContext context)
|
||||
{
|
||||
_logger.LogInformation($"接收到来自 {request.Name} 的请求");
|
||||
|
||||
// 构建并返回回复消息
|
||||
var reply = new HelloReply
|
||||
{
|
||||
Message = $"你好,{request.Name} 来自 gRPC 服务器!"
|
||||
};
|
||||
|
||||
// 返回一个 Task<HelloReply>
|
||||
return Task.FromResult(reply);
|
||||
}
|
||||
}
|
||||
}
|
||||
76
ZR.Admin.Grpc/Services/MyDiaryService.cs
Normal file
76
ZR.Admin.Grpc/Services/MyDiaryService.cs
Normal file
@ -0,0 +1,76 @@
|
||||
using Grpc.Core;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using ZR.Service.IService;
|
||||
|
||||
namespace ZR.Admin.Grpc.Services
|
||||
{
|
||||
public class MyDiaryService(ILogger<MyDiaryService> logger, IMyDiaryService myDiaryService) : MyDiary.MyDiaryBase
|
||||
{
|
||||
public override async Task<EditReply> Edit(EditRequest request, ServerCallContext context)
|
||||
{
|
||||
logger.LogInformation($"接收到来自 {request.UserId} 的请求");
|
||||
|
||||
var myDiary = new Model.MyDiary()
|
||||
{
|
||||
Content = request.Content,
|
||||
CreateTime = request.CreateTime.ToDateTime().ToLocalTime(),
|
||||
UserId = request.UserId
|
||||
};
|
||||
|
||||
var myDiaryToday = await myDiaryService.Queryable()
|
||||
.Where(it => it.CreateTime.Date == myDiary.CreateTime.Date && it.UserId == myDiary.UserId)
|
||||
.FirstAsync();
|
||||
if (myDiaryToday != null)
|
||||
{
|
||||
myDiaryToday.Content = myDiary.Content;
|
||||
await myDiaryService.Updateable(myDiaryToday)
|
||||
.ExecuteCommandAsync();
|
||||
}
|
||||
else
|
||||
{
|
||||
await myDiaryService.Insertable(myDiary).ExecuteReturnSnowflakeIdAsync();
|
||||
}
|
||||
|
||||
|
||||
|
||||
// 构建并返回回复消息
|
||||
var reply = new EditReply()
|
||||
{
|
||||
ResultMessage = $"日记已记录 来自 gRPC 服务器!"
|
||||
};
|
||||
|
||||
logger.LogInformation($"日记已记录");
|
||||
|
||||
// 返回一个 Task<HelloReply>
|
||||
return reply;
|
||||
}
|
||||
|
||||
public override async Task<QueryReply> Query(QueryRequest request, ServerCallContext context)
|
||||
{
|
||||
logger.LogInformation($"接收到来自 {request.UserId} 的请求");
|
||||
|
||||
var myDiary = new Model.MyDiary()
|
||||
{
|
||||
CreateTime = request.CreateTime.ToDateTime().ToLocalTime(),
|
||||
UserId = request.UserId
|
||||
};
|
||||
|
||||
var myDiaryToday = await myDiaryService.Queryable()
|
||||
.Where(it => it.CreateTime.Date == myDiary.CreateTime.Date && it.UserId == myDiary.UserId)
|
||||
.FirstAsync();
|
||||
|
||||
if (myDiaryToday != null)
|
||||
{
|
||||
myDiary.Content = myDiaryToday.Content;
|
||||
}
|
||||
|
||||
// 构建并返回回复消息
|
||||
var reply = new QueryReply()
|
||||
{
|
||||
Content = myDiary.Content ?? ""
|
||||
};
|
||||
|
||||
return reply;
|
||||
}
|
||||
}
|
||||
}
|
||||
28
ZR.Admin.Grpc/ZR.Admin.Grpc.csproj
Normal file
28
ZR.Admin.Grpc/ZR.Admin.Grpc.csproj
Normal file
@ -0,0 +1,28 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Remove="Services\FileTransferService.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Protobuf Include="Protos\greet.proto" GrpcServices="Both" />
|
||||
<Protobuf Include="Protos\block.proto" GrpcServices="Client" />
|
||||
<Protobuf Include="Protos\my_diary.proto" GrpcServices="Server" />
|
||||
<Protobuf Include="Protos\FileTransfer.proto" GrpcServices="Server" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Grpc.AspNetCore" Version="2.49.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\ZR.Service\ZR.Service.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@ -1,11 +1,12 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Infrastructure.Helper;
|
||||
using JinianNet.JNTemplate;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Newtonsoft.Json;
|
||||
using ZR.Admin.WebApi.Filters;
|
||||
using ZR.Model.System;
|
||||
using ZR.Service.IService;
|
||||
using ZR.Service.System;
|
||||
using ZR.Service.System.IService;
|
||||
using ZR.ServiceCore.Model;
|
||||
using ZR.ServiceCore.Services.IService;
|
||||
|
||||
namespace ZR.Admin.WebApi.Controllers
|
||||
{
|
||||
@ -44,8 +45,11 @@ namespace ZR.Admin.WebApi.Controllers
|
||||
[HttpGet]
|
||||
public IActionResult Index()
|
||||
{
|
||||
return Ok("看到这里页面说明你已经成功启动了本项目:)\n\n" +
|
||||
"如果觉得项目有用,打赏作者喝杯咖啡作为奖励\n☛☛http://www.izhaorui.cn/doc/support.html\n");
|
||||
var contentTpl = JnHelper.ReadTemplate("", "logo.txt");
|
||||
var content = contentTpl?.Render();
|
||||
// return Ok("看到这里页面说明你已经成功启动了本项目:)\n\n" +
|
||||
// $"{content}如果觉得项目有用,打赏作者喝杯咖啡作为奖励\n☛☛http://www.izhaorui.cn/doc/support.html\n");
|
||||
return Ok($"{content}\n\n看到这里页面说明你已经成功启动了本项目:)\n");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -126,7 +130,7 @@ namespace ZR.Admin.WebApi.Controllers
|
||||
SysFile file = new();
|
||||
string fileExt = Path.GetExtension(formFile.FileName);//文件后缀
|
||||
double fileSize = Math.Round(formFile.Length / 1024.0, 2);//文件大小KB
|
||||
|
||||
|
||||
if (OptionsSetting.Upload.NotAllowedExt.Contains(fileExt))
|
||||
{
|
||||
return ToResponse(ResultCode.CUSTOM_ERROR, "上传失败,未经允许上传类型");
|
||||
@ -147,7 +151,8 @@ namespace ZR.Admin.WebApi.Controllers
|
||||
{
|
||||
uploadDto.FileDir = OptionsSetting.Upload.LocalSavePath;
|
||||
}
|
||||
file = await SysFileService.SaveFileToLocal(savePath, uploadDto.FileName, uploadDto.FileDir, HttpContext.GetName(), formFile);
|
||||
file = await SysFileService.SaveFileToLocal(savePath, uploadDto.FileName, uploadDto.FileDir,
|
||||
HttpContext.GetUId(), HttpContext.GetNickName(), formFile, OptionsSetting.Upload.UploadUrl);
|
||||
break;
|
||||
case StoreType.REMOTE:
|
||||
break;
|
||||
@ -161,7 +166,8 @@ namespace ZR.Admin.WebApi.Controllers
|
||||
{
|
||||
return ToResponse(ResultCode.CUSTOM_ERROR, "上传文件过大,不能超过 " + AlimaxContentLength + " MB");
|
||||
}
|
||||
file = new(formFile.FileName, uploadDto.FileName, fileExt, fileSize + "kb", uploadDto.FileDir, HttpContext.GetName())
|
||||
file = new(formFile.FileName, uploadDto.FileName, fileExt, fileSize + "kb",
|
||||
uploadDto.FileDir, HttpContext.GetUId(), HttpContext.GetNickName())
|
||||
{
|
||||
StoreType = (int)StoreType.ALIYUN,
|
||||
FileType = formFile.ContentType
|
||||
|
||||
@ -1,9 +1,10 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using ZR.Admin.WebApi.Extensions;
|
||||
using ZR.Admin.WebApi.Filters;
|
||||
using ZR.Model.Dto;
|
||||
using ZR.Model.System;
|
||||
using ZR.Service.System.IService;
|
||||
using ZR.ServiceCore.Model;
|
||||
using ZR.ServiceCore.Model.Dto;
|
||||
|
||||
namespace ZR.Admin.WebApi.Controllers
|
||||
{
|
||||
|
||||
@ -2,9 +2,12 @@
|
||||
using SqlSugar;
|
||||
using ZR.Admin.WebApi.Extensions;
|
||||
using ZR.Admin.WebApi.Filters;
|
||||
using ZR.Model;
|
||||
using ZR.Model.System;
|
||||
using ZR.Model.System.Dto;
|
||||
using ZR.Service.System.IService;
|
||||
using ZR.ServiceCore.Filters;
|
||||
using ZR.ServiceCore.Model;
|
||||
using ZR.ServiceCore.Model.Dto;
|
||||
|
||||
namespace ZR.Admin.WebApi.Controllers
|
||||
{
|
||||
@ -33,7 +36,8 @@ namespace ZR.Admin.WebApi.Controllers
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
[HttpGet("list")]
|
||||
[ActionPermissionFilter(RolePermi = "admin")]
|
||||
// [ActionPermissionFilter(RolePermi = "admin")]
|
||||
[DataFieldFilter(typeof(PagedInfo<ArticleDto>))]
|
||||
public IActionResult Query([FromQuery] ArticleQueryDto parm)
|
||||
{
|
||||
var response = _ArticleService.GetList(parm);
|
||||
|
||||
45
ZR.Admin.WebApi/Controllers/System/BaseCodeRuleController.cs
Normal file
45
ZR.Admin.WebApi/Controllers/System/BaseCodeRuleController.cs
Normal file
@ -0,0 +1,45 @@
|
||||
using ZR.Model;
|
||||
using ZR.Model.System;
|
||||
using ZR.ServiceCore.Services.IService;
|
||||
|
||||
namespace ZR.Admin.WebApi.Controllers.System;
|
||||
[Route("base/codeRule")]
|
||||
public class BaseCodeRuleController : BaseController
|
||||
{
|
||||
private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();
|
||||
|
||||
private readonly IBaseCodeRuleService _baseCodeRuleService;
|
||||
|
||||
public BaseCodeRuleController(IBaseCodeRuleService baseCodeRuleService)
|
||||
{
|
||||
_baseCodeRuleService = baseCodeRuleService;
|
||||
}
|
||||
|
||||
[HttpPost("addBaseCodeRule")]
|
||||
public async Task<IActionResult> AddBaseCodeRule([FromBody] BaseCodeRule baseCodeRule)
|
||||
{
|
||||
var result = await _baseCodeRuleService.InsertBaseCodeRuleAsync(baseCodeRule);
|
||||
return SUCCESS(result);
|
||||
}
|
||||
|
||||
[HttpDelete("deleteBaseCodeRule/{code}")]
|
||||
public async Task<IActionResult> DeleteBaseCodeRule(string code)
|
||||
{
|
||||
var result = await _baseCodeRuleService.DeleteBaseCodeRuleAsync(code);
|
||||
return SUCCESS(result);
|
||||
}
|
||||
|
||||
[HttpPut("updateBaseCodeRule")]
|
||||
public async Task<IActionResult> UpdateBaseCodeRule([FromBody] BaseCodeRule baseCodeRule)
|
||||
{
|
||||
var result = await _baseCodeRuleService.UpdateBaseCodeRule(baseCodeRule);
|
||||
return SUCCESS(result);
|
||||
}
|
||||
|
||||
[HttpGet("getBaseCodeRuleList")]
|
||||
public IActionResult GetBaseCodeRuleList([FromQuery] BaseCodeRule baseCodeRule, [FromQuery] PagerInfo pagerInfo)
|
||||
{
|
||||
var result = _baseCodeRuleService.SelectBaseCodeRulePage(baseCodeRule, pagerInfo);
|
||||
return SUCCESS(result);
|
||||
}
|
||||
}
|
||||
@ -6,9 +6,10 @@ using ZR.CodeGenerator;
|
||||
using ZR.CodeGenerator.Model;
|
||||
using ZR.CodeGenerator.Service;
|
||||
using ZR.Model;
|
||||
using ZR.Model.System.Dto;
|
||||
using ZR.Model.System.Generate;
|
||||
using ZR.Service.System.IService;
|
||||
using ZR.ServiceCore.Model.Dto;
|
||||
using ZR.ServiceCore.Model.Generate;
|
||||
using ZR.ServiceCore.Services.IService;
|
||||
|
||||
namespace ZR.Admin.WebApi.Controllers
|
||||
{
|
||||
@ -304,7 +305,8 @@ namespace ZR.Admin.WebApi.Controllers
|
||||
if (string.IsNullOrEmpty(tableName) || tableId <= 0) throw new CustomException("参数错误");
|
||||
GenTable table = GenTableService.GetGenTableInfo(tableId);
|
||||
if (table == null) { throw new CustomException("同步数据失败,原表结构不存在"); }
|
||||
table.Update_by = HttpContext.GetName();
|
||||
table.Update_by = HttpContext.GetUId();
|
||||
table.Update_name = HttpContext.GetNickName();
|
||||
|
||||
List<DbColumnInfo> dbColumnInfos = _CodeGeneraterService.GetColumnInfo(table.DbName, tableName);
|
||||
List<GenTableColumn> dbTableColumns = CodeGeneratorTool.InitGenTableColumn(table, dbColumnInfos);
|
||||
|
||||
@ -3,9 +3,9 @@ using Microsoft.AspNetCore.Mvc;
|
||||
using MiniExcelLibs;
|
||||
using ZR.Admin.WebApi.Filters;
|
||||
using ZR.Model;
|
||||
using ZR.Model.Dto;
|
||||
using ZR.Model.Models;
|
||||
using ZR.Service.System.IService;
|
||||
using ZR.ServiceCore.Model;
|
||||
using ZR.ServiceCore.Model.Dto;
|
||||
|
||||
namespace ZR.Admin.WebApi.Controllers
|
||||
{
|
||||
@ -177,15 +177,16 @@ namespace ZR.Admin.WebApi.Controllers
|
||||
public IActionResult ImportData([FromForm(Name = "file")] IFormFile formFile)
|
||||
{
|
||||
List<CommonLang> list = new();
|
||||
var nowTime = DateTime.Now;
|
||||
using (var stream = formFile.OpenReadStream())
|
||||
{
|
||||
var rows = stream.Query(startCell: "A2").ToList();
|
||||
|
||||
foreach (var item in rows)
|
||||
{
|
||||
list.Add(new CommonLang() { LangCode = "zh-cn", LangKey = item.A, LangName = item.B, Addtime = DateTime.Now });
|
||||
list.Add(new CommonLang() { LangCode = "en", LangKey = item.A, LangName = item.C, Addtime = DateTime.Now });
|
||||
list.Add(new CommonLang() { LangCode = "zh-tw", LangKey = item.A, LangName = item.D, Addtime = DateTime.Now });
|
||||
list.Add(new CommonLang() { LangCode = "zh-cn", LangKey = item.A, LangName = item.B, Addtime = nowTime });
|
||||
list.Add(new CommonLang() { LangCode = "en", LangKey = item.A, LangName = item.C, Addtime = nowTime });
|
||||
list.Add(new CommonLang() { LangCode = "zh-tw", LangKey = item.A, LangName = item.D, Addtime = nowTime });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -4,8 +4,9 @@ using SqlSugar;
|
||||
using ZR.Admin.WebApi.Extensions;
|
||||
using ZR.Admin.WebApi.Filters;
|
||||
using ZR.Model.System;
|
||||
using ZR.Model.System.Dto;
|
||||
using ZR.Service.System.IService;
|
||||
using ZR.ServiceCore.Model;
|
||||
using ZR.ServiceCore.Model.Dto;
|
||||
|
||||
namespace ZR.Admin.WebApi.Controllers
|
||||
{
|
||||
|
||||
@ -2,8 +2,9 @@
|
||||
using System.Collections;
|
||||
using ZR.Admin.WebApi.Filters;
|
||||
using ZR.Model.System;
|
||||
using ZR.Model.System.Dto;
|
||||
using ZR.Service.System.IService;
|
||||
using ZR.ServiceCore.Model;
|
||||
using ZR.ServiceCore.Model.Dto;
|
||||
|
||||
namespace ZR.Admin.WebApi.Controllers.System
|
||||
{
|
||||
@ -114,7 +115,8 @@ namespace ZR.Admin.WebApi.Controllers.System
|
||||
{
|
||||
return ToResponse(ResultCode.CUSTOM_ERROR, $"新增部门{dept.DeptName}失败,部门名称已存在");
|
||||
}
|
||||
dept.Create_by = HttpContext.GetName();
|
||||
dept.Create_by = HttpContext.GetUId();
|
||||
dept.Create_name = HttpContext.GetNickName();
|
||||
return ToResponse(DeptService.InsertDept(dept));
|
||||
}
|
||||
|
||||
@ -136,7 +138,8 @@ namespace ZR.Admin.WebApi.Controllers.System
|
||||
{
|
||||
return ToResponse(ResultCode.CUSTOM_ERROR, $"修改部门{dept.DeptName}失败,上级部门不能是自己");
|
||||
}
|
||||
dept.Update_by = HttpContext.GetName();
|
||||
dept.Update_by = HttpContext.GetUId();
|
||||
dept.Update_name = HttpContext.GetNickName();
|
||||
return ToResponse(DeptService.UpdateDept(dept));
|
||||
}
|
||||
|
||||
|
||||
@ -2,8 +2,9 @@
|
||||
using ZR.Admin.WebApi.Filters;
|
||||
using ZR.Model;
|
||||
using ZR.Model.System;
|
||||
using ZR.Model.System.Dto;
|
||||
using ZR.Service.System.IService;
|
||||
using ZR.ServiceCore.Model;
|
||||
using ZR.ServiceCore.Model.Dto;
|
||||
|
||||
namespace ZR.Admin.WebApi.Controllers.System
|
||||
{
|
||||
@ -65,14 +66,14 @@ namespace ZR.Admin.WebApi.Controllers.System
|
||||
/// <returns></returns>
|
||||
[AllowAnonymous]
|
||||
[HttpPost("types")]
|
||||
public IActionResult DictTypes([FromBody] List<SysdictDataDto> dto)
|
||||
public IActionResult DictTypes([FromBody] List<SysDictDataDto> dto)
|
||||
{
|
||||
var list = SysDictDataService.SelectDictDataByTypes(dto.Select(f => f.DictType).ToArray());
|
||||
List<SysdictDataDto> dataVos = new();
|
||||
List<SysDictDataDto> dataVos = new();
|
||||
|
||||
foreach (var dic in dto)
|
||||
{
|
||||
SysdictDataDto vo = new()
|
||||
SysDictDataDto vo = new()
|
||||
{
|
||||
DictType = dic.DictType,
|
||||
ColumnName = dic.ColumnName,
|
||||
@ -109,7 +110,8 @@ namespace ZR.Admin.WebApi.Controllers.System
|
||||
[HttpPost()]
|
||||
public IActionResult Add([FromBody] SysDictData dict)
|
||||
{
|
||||
dict.Create_by = HttpContext.GetName();
|
||||
dict.Create_by = HttpContext.GetUId();
|
||||
dict.Create_name = HttpContext.GetNickName();
|
||||
dict.Create_time = DateTime.Now;
|
||||
return SUCCESS(SysDictDataService.InsertDictData(dict));
|
||||
}
|
||||
@ -124,7 +126,8 @@ namespace ZR.Admin.WebApi.Controllers.System
|
||||
[HttpPut()]
|
||||
public IActionResult Edit([FromBody] SysDictData dict)
|
||||
{
|
||||
dict.Update_by = HttpContext.GetName();
|
||||
dict.Update_by = HttpContext.GetUId();
|
||||
dict.Update_name = HttpContext.GetNickName();
|
||||
return SUCCESS(SysDictDataService.UpdateDictData(dict));
|
||||
}
|
||||
|
||||
|
||||
@ -3,8 +3,9 @@ using ZR.Admin.WebApi.Extensions;
|
||||
using ZR.Admin.WebApi.Filters;
|
||||
using ZR.Model;
|
||||
using ZR.Model.System;
|
||||
using ZR.Model.System.Dto;
|
||||
using ZR.Service.System.IService;
|
||||
using ZR.ServiceCore.Model;
|
||||
using ZR.ServiceCore.Model.Dto;
|
||||
|
||||
namespace ZR.Admin.WebApi.Controllers.System
|
||||
{
|
||||
@ -65,7 +66,8 @@ namespace ZR.Admin.WebApi.Controllers.System
|
||||
{
|
||||
return ToResponse(ApiResult.Error($"新增字典'{dict.DictName}'失败,字典类型已存在"));
|
||||
}
|
||||
dict.Create_by = HttpContext.GetName();
|
||||
dict.Create_by = HttpContext.GetUId();
|
||||
dict.Create_name = HttpContext.GetNickName();
|
||||
dict.Create_time = DateTime.Now;
|
||||
return SUCCESS(SysDictService.InsertDictType(dict));
|
||||
}
|
||||
@ -87,7 +89,8 @@ namespace ZR.Admin.WebApi.Controllers.System
|
||||
return ToResponse(ApiResult.Error($"修改字典'{dict.DictName}'失败,字典类型已存在"));
|
||||
}
|
||||
//设置添加人
|
||||
dict.Update_by = HttpContext.GetName();
|
||||
dict.Update_by = HttpContext.GetUId();
|
||||
dict.Update_name = HttpContext.GetNickName();
|
||||
return SUCCESS(SysDictService.UpdateDictType(dict));
|
||||
}
|
||||
|
||||
|
||||
62
ZR.Admin.WebApi/Controllers/System/SysFieldController.cs
Normal file
62
ZR.Admin.WebApi/Controllers/System/SysFieldController.cs
Normal file
@ -0,0 +1,62 @@
|
||||
using ZR.Admin.WebApi.Filters;
|
||||
using ZR.Model;
|
||||
using ZR.ServiceCore.Model;
|
||||
using ZR.ServiceCore.Model.Dto;
|
||||
using ZR.ServiceCore.Services.IService;
|
||||
|
||||
namespace ZR.Admin.WebApi.Controllers.System;
|
||||
|
||||
[Verify]
|
||||
[Route("system/field")]
|
||||
public class SysFieldController : BaseController
|
||||
{
|
||||
private readonly ISysFieldService _sysFieldService;
|
||||
private readonly ISysRoleFieldService _sysRoleFieldService;
|
||||
|
||||
public SysFieldController(ISysFieldService sysFieldService, ISysRoleFieldService sysRoleFieldService)
|
||||
{
|
||||
_sysFieldService = sysFieldService;
|
||||
_sysRoleFieldService = sysRoleFieldService;
|
||||
}
|
||||
|
||||
[HttpGet("getModelList")]
|
||||
public async Task<IActionResult> GetModelList([FromQuery] PagerInfo pagerInfo)
|
||||
=> SUCCESS(await _sysFieldService.GetModelList(pagerInfo));
|
||||
|
||||
[HttpGet("getFields")]
|
||||
public async Task<IActionResult> GetFields([FromQuery] string fullName, long roleId)
|
||||
=> SUCCESS(await _sysFieldService.GetFields(fullName, roleId));
|
||||
|
||||
[HttpPost("initFields")]
|
||||
public async Task<IActionResult> InitFields()
|
||||
=> SUCCESS(await _sysFieldService.InitFields());
|
||||
|
||||
[HttpPut("addOrUpdateSysRoleField/{roleId}")]
|
||||
public async Task<IActionResult> AddOrUpdateSysRoleField([FromBody] List<SysFieldDto> sysFieldDtos,
|
||||
[FromRoute] long roleId)
|
||||
=> SUCCESS(await _sysRoleFieldService.InsertOrUpdateSysRoleField(sysFieldDtos, roleId));
|
||||
|
||||
[HttpPost("fieldDisplay")]
|
||||
public async Task<IActionResult> FieldDisplay(string blockCode)
|
||||
{
|
||||
var info = JwtUtil.GetLoginUser(HttpContext);
|
||||
var roleIds = info.Roles.Select(it => it.RoleId).ToList();
|
||||
var list = await _sysFieldService.Queryable()
|
||||
.LeftJoin<SysFieldBlock>((sf, sfb) => sf.Id == sfb.FieldId)
|
||||
.LeftJoin<SysBlock>((sf, sfb, sb) => sfb.BlockId == sb.Id )
|
||||
.LeftJoin<SysRoleField>((sf,sfb, sb, srf) => sf.Id == srf.FieldId)
|
||||
.Where((sf,sfb, sb, srf) => roleIds.Contains(srf.RoleId))
|
||||
.Where((sf,sfb, sb, srf) => sb.Code == blockCode)
|
||||
.WithCache(10 * 60)
|
||||
.Select((sf,sfb, sb, srf) => sf.FieldName)
|
||||
.ToListAsync();
|
||||
// var list = await _sysFieldService.Queryable()
|
||||
// .LeftJoin<SysRoleField>((sf, srf) => sf.Id == srf.FieldId)
|
||||
// .Where((sf, srf) => roleIds.Contains(srf.RoleId))
|
||||
// .WithCache(10 * 60)
|
||||
// .Select((sf, srf) => sf.FieldName)
|
||||
// .ToListAsync();
|
||||
return SUCCESS(list);
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,9 +1,9 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using NLog;
|
||||
using SqlSugar;
|
||||
using ZR.Admin.WebApi.Filters;
|
||||
using ZR.Model.System;
|
||||
using ZR.Model.System.Dto;
|
||||
using ZR.Service.System.IService;
|
||||
using ZR.ServiceCore.Model;
|
||||
using ZR.ServiceCore.Model.Dto;
|
||||
using ZR.ServiceCore.Services.IService;
|
||||
|
||||
namespace ZR.Admin.WebApi.Controllers
|
||||
{
|
||||
@ -18,12 +18,14 @@ namespace ZR.Admin.WebApi.Controllers
|
||||
/// <summary>
|
||||
/// 文件存储接口
|
||||
/// </summary>
|
||||
private readonly ISysFileService _SysFileService;
|
||||
private readonly ISysFileService _sysFileService;
|
||||
|
||||
public SysFileController(ISysFileService SysFileService)
|
||||
public SysFileController(ISysFileService sysFileService)
|
||||
{
|
||||
_SysFileService = SysFileService;
|
||||
_sysFileService = sysFileService;
|
||||
}
|
||||
|
||||
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
|
||||
|
||||
/// <summary>
|
||||
/// 查询文件存储列表
|
||||
@ -41,7 +43,7 @@ namespace ZR.Admin.WebApi.Controllers
|
||||
predicate = predicate.AndIF(parm.StoreType != null, m => m.StoreType == parm.StoreType);
|
||||
predicate = predicate.AndIF(parm.FileId != null, m => m.Id == parm.FileId);
|
||||
|
||||
var response = _SysFileService.GetPages(predicate.ToExpression(), parm, x => x.Id, OrderByType.Desc);
|
||||
var response = _sysFileService.GetPages(predicate.ToExpression(), parm, x => x.Id, OrderByType.Desc);
|
||||
return SUCCESS(response);
|
||||
}
|
||||
|
||||
@ -54,7 +56,7 @@ namespace ZR.Admin.WebApi.Controllers
|
||||
[ActionPermissionFilter(Permission = "tool:file:query")]
|
||||
public IActionResult GetSysFile(long Id)
|
||||
{
|
||||
var response = _SysFileService.GetFirst(x => x.Id == Id);
|
||||
var response = _sysFileService.GetFirst(x => x.Id == Id);
|
||||
|
||||
return SUCCESS(response);
|
||||
}
|
||||
@ -66,13 +68,12 @@ namespace ZR.Admin.WebApi.Controllers
|
||||
[HttpDelete("{ids}")]
|
||||
[ActionPermissionFilter(Permission = "tool:file:delete")]
|
||||
[Log(Title = "文件存储", BusinessType = BusinessType.DELETE)]
|
||||
public IActionResult DeleteSysFile(string ids)
|
||||
public async Task<IActionResult> DeleteSysFile(string ids)
|
||||
{
|
||||
long[] idsArr = Tools.SpitLongArrary(ids);
|
||||
if (idsArr.Length <= 0) { return ToResponse(ApiResult.Error($"删除失败Id 不能为空")); }
|
||||
|
||||
var response = _SysFileService.Delete(idsArr);
|
||||
//TODO 删除本地资源
|
||||
var response = await _sysFileService.DeleteSysFileAsync(idsArr);
|
||||
|
||||
return ToResponse(response);
|
||||
}
|
||||
@ -86,10 +87,89 @@ namespace ZR.Admin.WebApi.Controllers
|
||||
[ActionPermissionFilter(Permission = "tool:file:export")]
|
||||
public IActionResult Export()
|
||||
{
|
||||
var list = _SysFileService.GetAll();
|
||||
var list = _sysFileService.GetAll();
|
||||
|
||||
string sFileName = ExportExcel(list, "SysFile", "文件存储");
|
||||
return SUCCESS(new { path = "/export/" + sFileName, fileName = sFileName });
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 通过文件ID下载文件
|
||||
/// </summary>
|
||||
/// <param name="file"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPost("download")]
|
||||
public IActionResult Download([FromBody] SysFile file)
|
||||
{
|
||||
var sysFile = _sysFileService.Queryable().Where(it => it.Id == file.Id).First();
|
||||
if (sysFile == null)
|
||||
{
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
Stream? stream = null;
|
||||
switch ((StoreType)Enum.Parse(typeof(StoreType), sysFile.StoreType.ToString() ?? string.Empty))
|
||||
{
|
||||
case StoreType.LOCAL:
|
||||
stream = sysFile.IsEncrypted == "1" ? _sysFileService.DecryptSysFileStream(sysFile.FileUrl)
|
||||
: new FileStream(sysFile.FileUrl, FileMode.Open);
|
||||
break;
|
||||
case StoreType.ALIYUN:
|
||||
stream = AliyunOssHelper.DownloadFile(sysFile.FileUrl, "", sysFile.IsEncrypted == "1");
|
||||
break;
|
||||
default:
|
||||
throw new CustomException("不支持的存储类型");
|
||||
}
|
||||
if (stream != null)
|
||||
{
|
||||
return new FileStreamResult(stream, "application/octet-stream")
|
||||
{
|
||||
FileDownloadName = sysFile.RealName
|
||||
};
|
||||
}
|
||||
else
|
||||
{
|
||||
return NoContent();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 通过文件ID下载文件
|
||||
/// </summary>
|
||||
/// <param name="fileId"></param>
|
||||
/// <returns></returns>
|
||||
[HttpGet("download/{fileId}")]
|
||||
public IActionResult Download([FromRoute] long fileId)
|
||||
{
|
||||
var sysFile = _sysFileService.Queryable().Where(it => it.Id == fileId).First();
|
||||
if (sysFile == null)
|
||||
{
|
||||
throw new CustomException("服务器上不存在此文件");
|
||||
}
|
||||
|
||||
Stream? stream;
|
||||
switch ((StoreType)Enum.Parse(typeof(StoreType), sysFile.StoreType.ToString() ?? string.Empty))
|
||||
{
|
||||
case StoreType.LOCAL:
|
||||
Logger.Info("本地存储");
|
||||
stream = sysFile.IsEncrypted == "1" ? _sysFileService.DecryptSysFileStream(sysFile.FileUrl)
|
||||
: new FileStream(sysFile.FileUrl, FileMode.Open);
|
||||
break;
|
||||
case StoreType.ALIYUN:
|
||||
stream = AliyunOssHelper.DownloadFile(sysFile.FileUrl, "", sysFile.IsEncrypted == "1");
|
||||
break;
|
||||
default:
|
||||
throw new CustomException("不支持的存储类型");
|
||||
}
|
||||
if (stream != null)
|
||||
{
|
||||
return new FileStreamResult(stream, "application/octet-stream")
|
||||
{
|
||||
FileDownloadName = sysFile.RealName
|
||||
};
|
||||
}
|
||||
|
||||
return NoContent();
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,11 +1,13 @@
|
||||
using Lazy.Captcha.Core;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Options;
|
||||
using NETCore.Encrypt;
|
||||
using ZR.Admin.WebApi.Filters;
|
||||
using ZR.Model.System;
|
||||
using ZR.Model.System.Dto;
|
||||
using ZR.Infrastructure.Cache;
|
||||
using ZR.Service.System;
|
||||
using ZR.Service.System.IService;
|
||||
using ZR.ServiceCore.Model;
|
||||
using ZR.ServiceCore.Model.Dto;
|
||||
using ZR.ServiceCore.Services.IService;
|
||||
|
||||
namespace ZR.Admin.WebApi.Controllers.System
|
||||
{
|
||||
@ -47,7 +49,9 @@ namespace ZR.Admin.WebApi.Controllers.System
|
||||
roleService = sysRoleService;
|
||||
this.optionSettings = optionSettings.Value;
|
||||
}
|
||||
|
||||
|
||||
// RSA私钥
|
||||
private static readonly string PrivatePem = AppSettings.GetConfig("RSA:PrivatePem");
|
||||
|
||||
/// <summary>
|
||||
/// 登录
|
||||
@ -61,14 +65,21 @@ namespace ZR.Admin.WebApi.Controllers.System
|
||||
{
|
||||
if (loginBody == null) { throw new CustomException("请求参数错误"); }
|
||||
loginBody.LoginIP = HttpContextExtension.GetClientUserIp(HttpContext);
|
||||
SysConfig sysConfig = sysConfigService.GetSysConfigByKey("sys.account.captchaOnOff");
|
||||
if (sysConfig?.ConfigValue != "off" && !SecurityCodeHelper.Validate(loginBody.Uuid, loginBody.Code))
|
||||
var sysConfig = sysConfigService.GetSysConfigByKey("sys.account.captchaOnOff");
|
||||
var headers = HttpContext.Request.Headers;
|
||||
var isRemoteInvoke = headers["Remote-Invoke"].FirstOrDefault().ParseToBool();
|
||||
if (sysConfig?.ConfigValue != "off" && !SecurityCodeHelper.Validate(loginBody.Uuid, loginBody.Code)
|
||||
&& !isRemoteInvoke)
|
||||
{
|
||||
return ToResponse(ResultCode.CAPTCHA_ERROR, "验证码错误");
|
||||
}
|
||||
|
||||
sysLoginService.CheckLockUser(loginBody.Username);
|
||||
string location = HttpContextExtension.GetIpInfo(loginBody.LoginIP);
|
||||
|
||||
// RSA解密
|
||||
loginBody.Password = EncryptProvider.RSADecryptWithPem(PrivatePem, loginBody.Password);
|
||||
|
||||
var user = sysLoginService.Login(loginBody, new SysLogininfor() { LoginLocation = location });
|
||||
|
||||
List<SysRole> roles = roleService.SelectUserRoleListByUserId(user.UserId);
|
||||
@ -130,7 +141,7 @@ namespace ZR.Admin.WebApi.Controllers.System
|
||||
public IActionResult GetRouters()
|
||||
{
|
||||
long uid = HttpContext.GetUId();
|
||||
var menus = sysMenuService.SelectMenuTreeByUserId(uid);
|
||||
var menus = sysMenuService.SelectMenuTreeByUserId(uid);
|
||||
|
||||
return SUCCESS(sysMenuService.BuildMenus(menus));
|
||||
}
|
||||
@ -181,6 +192,64 @@ namespace ZR.Admin.WebApi.Controllers.System
|
||||
return ToResponse(ResultCode.CUSTOM_ERROR, "注册失败,请联系管理员");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 发送邮箱验证码
|
||||
/// </summary>
|
||||
/// <param name="sendEmailVo"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPost("getMailCode")]
|
||||
public async Task<IActionResult> GetMailCode([FromBody] SendEmailDto sendEmailVo)
|
||||
{
|
||||
if (string.IsNullOrEmpty(sendEmailVo.ToUser))
|
||||
{
|
||||
return ToResponse(ApiResult.Error($"邮箱不能为空"));
|
||||
}
|
||||
if (string.IsNullOrEmpty(optionSettings.MailOptions.FromEmail) || string.IsNullOrEmpty(optionSettings.MailOptions.Password))
|
||||
{
|
||||
return ToResponse(ApiResult.Error($"请配置邮箱信息"));
|
||||
}
|
||||
|
||||
if (sendEmailVo.ToUser.Length > 32)
|
||||
{
|
||||
// 解密邮箱
|
||||
sendEmailVo.ToUser = EncryptProvider.RSADecryptWithPem(PrivatePem, sendEmailVo.ToUser);
|
||||
|
||||
// 验证邮箱是否存在于系统用户中
|
||||
var user = await sysUserService.IsAnyAsync(it => it.Email == sendEmailVo.ToUser);
|
||||
// if (user == null || user.UserId <= 0)
|
||||
// 不存在则提示错误
|
||||
if (!user)
|
||||
{
|
||||
return ToResponse(ApiResult.Error($"邮箱错误,请联系管理员"));
|
||||
}
|
||||
|
||||
}
|
||||
else
|
||||
{
|
||||
string[] saltKey = await RedisServer.Session.LRangeAsync("saltMail:" + sendEmailVo.ToUser, 0, 1);
|
||||
if (saltKey.Length > 0)
|
||||
{
|
||||
sendEmailVo.ToUser = saltKey[0];
|
||||
}
|
||||
else
|
||||
{
|
||||
return ToResponse(ApiResult.Error($"邮箱错误,请联系管理员"));
|
||||
}
|
||||
}
|
||||
// 实例化MailHelper以准备发送邮件
|
||||
MailHelper mailHelper = new();
|
||||
// 生成6位邮箱验证码
|
||||
var verifyCode = mailHelper.VerifyCode(6);
|
||||
// 设置存入Redis的key为 verifyCode: 前缀 + (盐 + 邮箱)的MD5值
|
||||
var key = "verifyCode:" + sendEmailVo.ToUser;
|
||||
// 存入Redis中设置过期时间为15分钟
|
||||
var res = await RedisServer.Session.SetAsync(key, verifyCode, 900);
|
||||
// 发送邮件,主题为 ZRAdmin.NET邮箱验证码,内容为验证码
|
||||
mailHelper.SendMail(sendEmailVo.ToUser, "ZRAdmin.NET邮箱验证码", verifyCode);
|
||||
|
||||
return SUCCESS(res);
|
||||
}
|
||||
|
||||
#region 二维码登录
|
||||
|
||||
/// <summary>
|
||||
|
||||
@ -1,8 +1,10 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using ZR.Admin.WebApi.Filters;
|
||||
using ZR.Model.System;
|
||||
using ZR.Model.System.Dto;
|
||||
using ZR.Service.System.IService;
|
||||
using ZR.ServiceCore.Model;
|
||||
using ZR.ServiceCore.Model.Dto;
|
||||
using ZR.ServiceCore.Services.IService;
|
||||
|
||||
namespace ZR.Admin.WebApi.Controllers.System
|
||||
{
|
||||
@ -113,7 +115,8 @@ namespace ZR.Admin.WebApi.Controllers.System
|
||||
{
|
||||
return ToResponse(ApiResult.Error($"修改菜单'{modal.MenuName}'失败,上级菜单不能选择自己"));
|
||||
}
|
||||
modal.Update_by = HttpContext.GetName();
|
||||
modal.Update_by = HttpContext.GetUId();
|
||||
modal.Update_name = HttpContext.GetNickName();
|
||||
long result = sysMenuService.EditMenu(modal);
|
||||
|
||||
return ToResponse(result);
|
||||
@ -145,7 +148,8 @@ namespace ZR.Admin.WebApi.Controllers.System
|
||||
return ToResponse(ApiResult.Error($"新增菜单'{menu.MenuName}'失败,地址必须以http(s)://开头"));
|
||||
}
|
||||
|
||||
menu.Create_by = HttpContext.GetName();
|
||||
menu.Create_by = HttpContext.GetUId();
|
||||
menu.Create_name = HttpContext.GetNickName();
|
||||
long result = sysMenuService.AddMenu(menu);
|
||||
|
||||
return ToResponse(result);
|
||||
|
||||
@ -1,11 +1,15 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using Microsoft.AspNetCore.SignalR;
|
||||
using Microsoft.AspNetCore.SignalR.Client;
|
||||
using NLog;
|
||||
using SqlSugar;
|
||||
using ZR.Admin.WebApi.Filters;
|
||||
using ZR.Model;
|
||||
using ZR.Model.System;
|
||||
using ZR.Model.System.Dto;
|
||||
using ZR.Service.System.IService;
|
||||
using ZR.ServiceCore.Model;
|
||||
using ZR.ServiceCore.Model.Dto;
|
||||
using ZR.ServiceCore.Services.IService;
|
||||
using ZR.ServiceCore.Signalr;
|
||||
|
||||
namespace ZR.Admin.WebApi.Controllers.System
|
||||
@ -21,13 +25,17 @@ namespace ZR.Admin.WebApi.Controllers.System
|
||||
/// <summary>
|
||||
/// 通知公告表接口
|
||||
/// </summary>
|
||||
private readonly ISysNoticeService _SysNoticeService;
|
||||
private readonly ISysNoticeService _sysNoticeService;
|
||||
private readonly IHubContext<MessageHub> _hubContext;
|
||||
|
||||
public SysNoticeController(ISysNoticeService SysNoticeService, IHubContext<MessageHub> hubContext)
|
||||
private readonly ISysNoticeLogService _sysNoticeLogService;
|
||||
private readonly IWebHostEnvironment _webHostEnvironment;
|
||||
private readonly Logger Logger = LogManager.GetCurrentClassLogger();
|
||||
public SysNoticeController(ISysNoticeService sysNoticeService, IHubContext<MessageHub> hubContext, ISysNoticeLogService sysNoticeLogService, IWebHostEnvironment webHostEnvironment)
|
||||
{
|
||||
_SysNoticeService = SysNoticeService;
|
||||
_sysNoticeService = sysNoticeService;
|
||||
_hubContext = hubContext;
|
||||
_sysNoticeLogService = sysNoticeLogService;
|
||||
_webHostEnvironment = webHostEnvironment;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -40,7 +48,7 @@ namespace ZR.Admin.WebApi.Controllers.System
|
||||
var predicate = Expressionable.Create<SysNotice>();
|
||||
|
||||
predicate = predicate.And(m => m.Status == 0);
|
||||
var response = _SysNoticeService.GetPages(predicate.ToExpression(), parm);
|
||||
var response = _sysNoticeService.GetPages(predicate.ToExpression(), parm);
|
||||
return SUCCESS(response);
|
||||
}
|
||||
|
||||
@ -52,19 +60,19 @@ namespace ZR.Admin.WebApi.Controllers.System
|
||||
[ActionPermissionFilter(Permission = "system:notice:list")]
|
||||
public IActionResult QuerySysNotice([FromQuery] SysNoticeQueryDto parm)
|
||||
{
|
||||
PagedInfo<SysNotice> response = _SysNoticeService.GetPageList(parm);
|
||||
PagedInfo<SysNotice> response = _sysNoticeService.GetPageList(parm);
|
||||
return SUCCESS(response);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 查询通知公告表详情
|
||||
/// </summary>
|
||||
/// <param name="NoticeId"></param>
|
||||
/// <param name="noticeId"></param>
|
||||
/// <returns></returns>
|
||||
[HttpGet("{NoticeId}")]
|
||||
public IActionResult GetSysNotice(int NoticeId)
|
||||
[HttpGet("{noticeId}")]
|
||||
public IActionResult GetSysNotice(long noticeId)
|
||||
{
|
||||
var response = _SysNoticeService.GetFirst(x => x.NoticeId == NoticeId);
|
||||
var response = _sysNoticeService.GetFirst(x => x.NoticeId == noticeId);
|
||||
|
||||
return SUCCESS(response);
|
||||
}
|
||||
@ -76,21 +84,41 @@ namespace ZR.Admin.WebApi.Controllers.System
|
||||
[HttpPost]
|
||||
[ActionPermissionFilter(Permission = "system:notice:add")]
|
||||
[Log(Title = "发布通告", BusinessType = BusinessType.INSERT)]
|
||||
public IActionResult AddSysNotice([FromBody] SysNoticeDto parm)
|
||||
public async Task<IActionResult> AddSysNotice([FromBody] SysNoticeDto parm)
|
||||
{
|
||||
var modal = parm.Adapt<SysNotice>().ToCreate(HttpContext);
|
||||
modal.Create_by = HttpContext.GetUId();
|
||||
modal.Create_name = HttpContext.GetNickName();
|
||||
modal.Create_time = DateTime.Now;
|
||||
|
||||
int result = _SysNoticeService.Insert(modal, it => new
|
||||
// int result = _SysNoticeService.Insert(modal, it => new
|
||||
// {
|
||||
// it.NoticeTitle,
|
||||
// it.NoticeType,
|
||||
// it.NoticeContent,
|
||||
// it.Status,
|
||||
// it.Remark,
|
||||
// it.Create_by,
|
||||
// it.Create_time
|
||||
// });
|
||||
|
||||
var result = await _sysNoticeService
|
||||
.Insertable(modal)
|
||||
.ExecuteReturnSnowflakeIdAsync();
|
||||
var scheme = HttpContext.Request.Scheme + "://";
|
||||
var serverIP = HttpContext.Request.Host.Value;
|
||||
if (_webHostEnvironment.IsProduction())
|
||||
{
|
||||
it.NoticeTitle,
|
||||
it.NoticeType,
|
||||
it.NoticeContent,
|
||||
it.Status,
|
||||
it.Remark,
|
||||
it.Create_by,
|
||||
it.Create_time
|
||||
});
|
||||
|
||||
var host = await Dns.GetHostEntryAsync(Dns.GetHostName());
|
||||
var ip = host.AddressList
|
||||
.FirstOrDefault(it => it.AddressFamily == AddressFamily.InterNetwork);
|
||||
serverIP = ip + ":" + Request.HttpContext.Connection.LocalPort;//获取服务器IP
|
||||
}
|
||||
var url = scheme + serverIP;
|
||||
var hubConnection = new HubConnectionBuilder().WithUrl(url + "/msghub").Build();
|
||||
await hubConnection.StartAsync();
|
||||
await hubConnection.InvokeAsync("SendNoticeToOnlineUsers", result, true);
|
||||
await hubConnection.StopAsync();
|
||||
return SUCCESS(result);
|
||||
}
|
||||
|
||||
@ -101,37 +129,56 @@ namespace ZR.Admin.WebApi.Controllers.System
|
||||
[HttpPut]
|
||||
[ActionPermissionFilter(Permission = "system:notice:update")]
|
||||
[Log(Title = "修改公告", BusinessType = BusinessType.UPDATE)]
|
||||
public IActionResult UpdateSysNotice([FromBody] SysNoticeDto parm)
|
||||
public async Task<IActionResult> UpdateSysNotice([FromBody] SysNoticeDto parm)
|
||||
{
|
||||
var model = parm.Adapt<SysNotice>().ToUpdate(HttpContext);
|
||||
model.Update_by = HttpContext.GetName();
|
||||
var response = _SysNoticeService.Update(w => w.NoticeId == model.NoticeId, it => new SysNotice()
|
||||
var config = new TypeAdapterConfig();
|
||||
config.ForType<SysNoticeDto, SysNotice>()
|
||||
.Map(dest => dest.NoticeId, src => src.NoticeId.ParseToLong());
|
||||
var model = parm.Adapt<SysNotice>(config).ToUpdate(HttpContext);
|
||||
var nowDate = DateTime.Now;
|
||||
var response = _sysNoticeService.Update(w => w.NoticeId == model.NoticeId, it => new SysNotice()
|
||||
{
|
||||
NoticeTitle = model.NoticeTitle,
|
||||
NoticeType = model.NoticeType,
|
||||
NoticeContent = model.NoticeContent,
|
||||
Status = model.Status,
|
||||
Remark = model.Remark,
|
||||
Update_by = HttpContext.GetName(),
|
||||
Update_time = DateTime.Now
|
||||
Update_by = HttpContext.GetUId(),
|
||||
Update_name = HttpContext.GetNickName(),
|
||||
Update_time = nowDate,
|
||||
Create_time = nowDate
|
||||
});
|
||||
|
||||
|
||||
var scheme = HttpContext.Request.Scheme + "://";
|
||||
var serverIP = HttpContext.Request.Host.Value;
|
||||
if (_webHostEnvironment.IsProduction())
|
||||
{
|
||||
var host = await Dns.GetHostEntryAsync(Dns.GetHostName());
|
||||
var ip = host.AddressList
|
||||
.FirstOrDefault(it => it.AddressFamily == AddressFamily.InterNetwork);
|
||||
serverIP = ip + ":" + Request.HttpContext.Connection.LocalPort;//获取服务器IP
|
||||
}
|
||||
var url = scheme + serverIP;
|
||||
var hubConnection = new HubConnectionBuilder().WithUrl(url + "/msghub").Build();
|
||||
await hubConnection.StartAsync();
|
||||
await hubConnection.InvokeAsync("SendNoticeToOnlineUsers", model.NoticeId, true);
|
||||
await hubConnection.StopAsync();
|
||||
return SUCCESS(response);
|
||||
}
|
||||
/// <summary>
|
||||
/// 发送通知公告表
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
[HttpPut("send/{NoticeId}")]
|
||||
[HttpPut("send/{noticeId}")]
|
||||
[ActionPermissionFilter(Permission = "system:notice:update")]
|
||||
[Log(Title = "发送通知公告", BusinessType = BusinessType.OTHER)]
|
||||
public IActionResult SendNotice(int NoticeId = 0)
|
||||
public IActionResult SendNotice(long noticeId = 0)
|
||||
{
|
||||
if (NoticeId <= 0)
|
||||
if (noticeId <= 0)
|
||||
{
|
||||
throw new CustomException("请求实体不能为空");
|
||||
}
|
||||
var response = _SysNoticeService.GetFirst(x => x.NoticeId == NoticeId);
|
||||
var response = _sysNoticeService.GetFirst(x => x.NoticeId == noticeId);
|
||||
if (response != null && response.Status == 0)
|
||||
{
|
||||
_hubContext.Clients.All.SendAsync(HubsConstant.ReceiveNotice, response.NoticeTitle, response.NoticeContent);
|
||||
@ -146,13 +193,30 @@ namespace ZR.Admin.WebApi.Controllers.System
|
||||
[HttpDelete("{ids}")]
|
||||
[ActionPermissionFilter(Permission = "system:notice:delete")]
|
||||
[Log(Title = "通知公告", BusinessType = BusinessType.DELETE)]
|
||||
public IActionResult DeleteSysNotice(string ids)
|
||||
public async Task<IActionResult> DeleteSysNotice(string ids)
|
||||
{
|
||||
int[] idsArr = Tools.SpitIntArrary(ids);
|
||||
var idsArr = Tools.SpitLongArrary(ids);
|
||||
if (idsArr.Length <= 0) { return ToResponse(ApiResult.Error($"删除失败Id 不能为空")); }
|
||||
|
||||
var response = _SysNoticeService.Delete(idsArr);
|
||||
|
||||
var response = _sysNoticeService.Delete(idsArr);
|
||||
await _sysNoticeLogService.Deleteable()
|
||||
.Where(it => idsArr.Contains(it.NoticeId))
|
||||
.ExecuteCommandAsync();
|
||||
|
||||
var scheme = HttpContext.Request.Scheme + "://";
|
||||
var serverIP = HttpContext.Request.Host.Value;
|
||||
if (_webHostEnvironment.IsProduction())
|
||||
{
|
||||
var host = await Dns.GetHostEntryAsync(Dns.GetHostName());
|
||||
var ip = host.AddressList
|
||||
.FirstOrDefault(it => it.AddressFamily == AddressFamily.InterNetwork);
|
||||
serverIP = ip + ":" + Request.HttpContext.Connection.LocalPort;//获取服务器IP
|
||||
}
|
||||
var url = scheme + serverIP;
|
||||
var hubConnection = new HubConnectionBuilder().WithUrl(url + "/msghub").Build();
|
||||
await hubConnection.StartAsync();
|
||||
await hubConnection.InvokeAsync("SendNoticeToOnlineUsers", null, false);
|
||||
await hubConnection.StopAsync();
|
||||
return SUCCESS(response);
|
||||
}
|
||||
}
|
||||
|
||||
@ -4,6 +4,7 @@ using ZR.Admin.WebApi.Filters;
|
||||
using ZR.Model;
|
||||
using ZR.Model.System;
|
||||
using ZR.Service.System.IService;
|
||||
using ZR.ServiceCore.Model;
|
||||
|
||||
namespace ZR.Admin.WebApi.Controllers.System
|
||||
{
|
||||
|
||||
@ -1,8 +1,9 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Options;
|
||||
using ZR.Admin.WebApi.Filters;
|
||||
using ZR.Model.System;
|
||||
using ZR.Model.System.Dto;
|
||||
using ZR.Service.System.IService;
|
||||
using ZR.ServiceCore.Model;
|
||||
using ZR.ServiceCore.Model.Dto;
|
||||
using ZR.ServiceCore.Services.IService;
|
||||
|
||||
namespace ZR.Admin.WebApi.Controllers.System
|
||||
{
|
||||
@ -20,6 +21,7 @@ namespace ZR.Admin.WebApi.Controllers.System
|
||||
private readonly ISysDeptService DeptService;
|
||||
private readonly ISysFileService FileService;
|
||||
private IWebHostEnvironment hostEnvironment;
|
||||
private readonly OptionsSetting _optionsSetting;
|
||||
|
||||
public SysProfileController(
|
||||
ISysUserService userService,
|
||||
@ -27,7 +29,8 @@ namespace ZR.Admin.WebApi.Controllers.System
|
||||
ISysUserPostService postService,
|
||||
ISysDeptService deptService,
|
||||
ISysFileService sysFileService,
|
||||
IWebHostEnvironment hostEnvironment)
|
||||
IWebHostEnvironment hostEnvironment,
|
||||
IOptions<OptionsSetting> options)
|
||||
{
|
||||
UserService = userService;
|
||||
RoleService = roleService;
|
||||
@ -35,6 +38,7 @@ namespace ZR.Admin.WebApi.Controllers.System
|
||||
DeptService = deptService;
|
||||
FileService = sysFileService;
|
||||
this.hostEnvironment = hostEnvironment;
|
||||
_optionsSetting = options.Value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -118,8 +122,10 @@ namespace ZR.Admin.WebApi.Controllers.System
|
||||
{
|
||||
long userId = HttpContext.GetUId();
|
||||
if (formFile == null) throw new CustomException("请选择文件");
|
||||
|
||||
SysFile file = await FileService.SaveFileToLocal(hostEnvironment.WebRootPath, "", "avatar", HttpContext.GetName(), formFile);
|
||||
|
||||
|
||||
var file = await FileService.SaveFileToLocal(hostEnvironment.WebRootPath, "", "avatar",
|
||||
HttpContext.GetUId(), HttpContext.GetName(), formFile, _optionsSetting.Upload.UploadUrl);
|
||||
|
||||
UserService.UpdatePhoto(new SysUser() { Avatar = file.AccessUrl, UserId = userId });
|
||||
return SUCCESS(new { imgUrl = file.AccessUrl });
|
||||
|
||||
@ -2,8 +2,10 @@
|
||||
using ZR.Admin.WebApi.Filters;
|
||||
using ZR.Model;
|
||||
using ZR.Model.System;
|
||||
using ZR.Model.System.Dto;
|
||||
using ZR.Service.System.IService;
|
||||
using ZR.ServiceCore.Model;
|
||||
using ZR.ServiceCore.Model.Dto;
|
||||
using ZR.ServiceCore.Services.IService;
|
||||
|
||||
namespace ZR.Admin.WebApi.Controllers.System
|
||||
{
|
||||
@ -70,7 +72,8 @@ namespace ZR.Admin.WebApi.Controllers.System
|
||||
return ToResponse(ApiResult.Error((int)ResultCode.CUSTOM_ERROR, $"新增角色'{sysRoleDto.RoleName}'失败,角色权限已存在"));
|
||||
}
|
||||
|
||||
sysRoleDto.Create_by = HttpContext.GetName();
|
||||
sysRoleDto.Create_by = HttpContext.GetUId();
|
||||
sysRoleDto.Create_name = HttpContext.GetNickName();
|
||||
long roleId = sysRoleService.InsertRole(sysRoleDto);
|
||||
|
||||
return ToResponse(roleId);
|
||||
@ -101,7 +104,8 @@ namespace ZR.Admin.WebApi.Controllers.System
|
||||
return ToResponse(ApiResult.Error($"编辑角色'{sysRoleDto.RoleName}'失败,角色权限已存在"));
|
||||
}
|
||||
}
|
||||
sysRoleDto.Update_by = HttpContext.GetName();
|
||||
sysRoleDto.Update_by = HttpContext.GetUId();
|
||||
sysRoleDto.Update_name = HttpContext.GetNickName();
|
||||
int upResult = sysRoleService.UpdateRole(sysRoleDto);
|
||||
if (upResult > 0)
|
||||
{
|
||||
@ -122,7 +126,8 @@ namespace ZR.Admin.WebApi.Controllers.System
|
||||
{
|
||||
if (sysRoleDto == null || sysRoleDto.RoleId <= 0) return ToResponse(ApiResult.Error(101, "请求参数错误"));
|
||||
SysRole sysRole = sysRoleDto.Adapt<SysRole>();
|
||||
sysRoleDto.Create_by = HttpContext.GetName();
|
||||
sysRoleDto.Create_by = HttpContext.GetUId();
|
||||
sysRoleDto.Create_name = HttpContext.GetNickName();
|
||||
sysRoleService.CheckRoleAllowed(sysRole);
|
||||
|
||||
bool result = sysRoleService.AuthDataScope(sysRoleDto);
|
||||
|
||||
@ -4,8 +4,9 @@ using SqlSugar;
|
||||
using ZR.Admin.WebApi.Filters;
|
||||
using ZR.Model;
|
||||
using ZR.Model.System;
|
||||
using ZR.Model.System.Dto;
|
||||
using ZR.Service.System.IService;
|
||||
using ZR.ServiceCore.Model;
|
||||
using ZR.ServiceCore.Model.Dto;
|
||||
|
||||
namespace ZR.Admin.WebApi.Controllers.System
|
||||
{
|
||||
@ -92,7 +93,8 @@ namespace ZR.Admin.WebApi.Controllers.System
|
||||
return ToResponse(ApiResult.Error($"新增用户 '{user.UserName}'失败,登录账号已存在"));
|
||||
}
|
||||
|
||||
user.Create_by = HttpContext.GetName();
|
||||
user.Create_by = HttpContext.GetUId();
|
||||
user.Create_name = HttpContext.GetNickName();
|
||||
user.Create_time = DateTime.Now;
|
||||
user.Password = NETCore.Encrypt.EncryptProvider.Md5(user.Password);
|
||||
|
||||
@ -111,7 +113,8 @@ namespace ZR.Admin.WebApi.Controllers.System
|
||||
{
|
||||
if (user == null || user.UserId <= 0) { return ToResponse(ApiResult.Error(101, "请求参数错误")); }
|
||||
|
||||
user.Update_by = HttpContext.GetName();
|
||||
user.Update_by = HttpContext.GetUId();
|
||||
user.Update_name = HttpContext.GetNickName();
|
||||
int upResult = UserService.UpdateUser(user);
|
||||
|
||||
return ToResponse(upResult);
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using ZR.Admin.WebApi.Filters;
|
||||
using ZR.Model.System.Dto;
|
||||
using ZR.Service.System.IService;
|
||||
using ZR.ServiceCore.Model.Dto;
|
||||
|
||||
namespace ZR.Admin.WebApi.Controllers.System
|
||||
{
|
||||
|
||||
@ -3,8 +3,9 @@ using Quartz;
|
||||
using SqlSugar;
|
||||
using ZR.Admin.WebApi.Filters;
|
||||
using ZR.Model.System;
|
||||
using ZR.Model.System.Dto;
|
||||
using ZR.Service.System.IService;
|
||||
using ZR.ServiceCore.Model;
|
||||
using ZR.ServiceCore.Model.Dto;
|
||||
using ZR.Tasks;
|
||||
|
||||
namespace ZR.Admin.WebApi.Controllers
|
||||
@ -87,7 +88,8 @@ namespace ZR.Admin.WebApi.Controllers
|
||||
}
|
||||
//从 Dto 映射到 实体
|
||||
var tasksQz = parm.Adapt<SysTasks>().ToCreate(HttpContext);
|
||||
tasksQz.Create_by = HttpContext.GetName();
|
||||
tasksQz.Create_by = HttpContext.GetUId();
|
||||
tasksQz.Create_name = HttpContext.GetNickName();
|
||||
tasksQz.ID = SnowFlakeSingle.Instance.NextId().ToString();
|
||||
|
||||
return SUCCESS(_tasksQzService.AddTasks(tasksQz));
|
||||
@ -126,7 +128,8 @@ namespace ZR.Admin.WebApi.Controllers
|
||||
throw new CustomException($"该任务正在运行中,请先停止在更新");
|
||||
}
|
||||
var model = parm.Adapt<SysTasks>();
|
||||
model.Update_by = HttpContextExtension.GetName(HttpContext);
|
||||
model.Update_by = HttpContext.GetUId();
|
||||
model.Update_name = HttpContext.GetNickName();
|
||||
int response = _tasksQzService.UpdateTasks(model);
|
||||
if (response > 0)
|
||||
{
|
||||
|
||||
@ -3,8 +3,9 @@ using SqlSugar;
|
||||
using ZR.Admin.WebApi.Filters;
|
||||
using ZR.Model;
|
||||
using ZR.Model.System;
|
||||
using ZR.Model.System.Dto;
|
||||
using ZR.Service.System.IService;
|
||||
using ZR.ServiceCore.Model;
|
||||
using ZR.ServiceCore.Model.Dto;
|
||||
|
||||
namespace ZR.Admin.WebApi.Controllers.System
|
||||
{
|
||||
|
||||
@ -0,0 +1,195 @@
|
||||
using AspNetCoreRateLimit;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Options;
|
||||
using ZR.Admin.WebApi.Filters;
|
||||
using ZR.Model;
|
||||
using ZR.ServiceCore.Model;
|
||||
using ZR.ServiceCore.Services.IService;
|
||||
using IpRateLimitPolicy = ZR.ServiceCore.Model.IpRateLimitPolicy;
|
||||
|
||||
namespace ZR.Admin.WebApi.Controllers.System.monitor;
|
||||
|
||||
[Verify]
|
||||
[Route("ip/route/limit")]
|
||||
public class IpRateLimitController : BaseController
|
||||
{
|
||||
private readonly IpRateLimitOptions _options;
|
||||
private readonly IIpPolicyStore _ipPolicyStore;
|
||||
private readonly IIpRateLimitPolicyService _ipRateLimitPolicyService;
|
||||
private readonly IRateLimitRuleService _rateLimitRuleService;
|
||||
private readonly IIpRateLimitLogService _ipRateLimitLogService;
|
||||
|
||||
public IpRateLimitController(IOptions<IpRateLimitOptions> optionsAccessor, IIpPolicyStore ipPolicyStore,
|
||||
IIpRateLimitPolicyService ipRateLimitPolicyService, IRateLimitRuleService rateLimitRuleService,
|
||||
IIpRateLimitLogService ipRateLimitLogService)
|
||||
{
|
||||
_options = optionsAccessor.Value;
|
||||
_ipPolicyStore = ipPolicyStore;
|
||||
_ipRateLimitPolicyService = ipRateLimitPolicyService;
|
||||
_rateLimitRuleService = rateLimitRuleService;
|
||||
_ipRateLimitLogService = ipRateLimitLogService;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取限制规则
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
[HttpGet("getIpRateLimitPolicyPage")]
|
||||
public async Task<IActionResult> GetIpRateLimitPolicyPage([FromQuery] IpRateLimitPolicy ipRateLimitPolicy,
|
||||
PagerInfo pager)
|
||||
{
|
||||
var page = await _ipRateLimitPolicyService.SelectIpRateLimitPolicyPageAsync(ipRateLimitPolicy, pager);
|
||||
return SUCCESS(page);
|
||||
}
|
||||
|
||||
[HttpPost("addIpRateLimitPolicy")]
|
||||
public async Task<IActionResult> AddIpRateLimitPolicy([FromBody] IpRateLimitPolicy ipRateLimitPolicy)
|
||||
{
|
||||
var isExist = await _ipRateLimitPolicyService.Queryable()
|
||||
.Where(it => it.Ip == ipRateLimitPolicy.Ip)
|
||||
.AnyAsync();
|
||||
if (isExist) throw new CustomException("该IP已存在");
|
||||
var res = await _ipRateLimitPolicyService.InsertNav(ipRateLimitPolicy)
|
||||
.Include(it => it.Rules)
|
||||
.ExecuteCommandAsync();
|
||||
return SUCCESS(res);
|
||||
}
|
||||
|
||||
[HttpPut("updateIpRateLimitPolicy")]
|
||||
public async Task<IActionResult> UpdateIpRateLimitPolicy(
|
||||
[FromBody] IpRateLimitPolicy ipRateLimitPolicy)
|
||||
{
|
||||
var isEnable = await _ipRateLimitPolicyService
|
||||
.Queryable()
|
||||
.Where(it => it.Id == ipRateLimitPolicy.Id
|
||||
&& it.Flag == '1')
|
||||
.AnyAsync();
|
||||
var res = await _ipRateLimitPolicyService.UpdateNav(ipRateLimitPolicy)
|
||||
.Include(it => it.Rules)
|
||||
.ExecuteCommandAsync();
|
||||
if (!isEnable) return SUCCESS(res);
|
||||
{
|
||||
await _ipPolicyStore.RemoveAsync(_options.IpPolicyPrefix);
|
||||
var ipRateLimitPolicies = _ipRateLimitPolicyService.Queryable()
|
||||
.Includes(it => it.Rules.Where(r => r.Flag == '1').ToList())
|
||||
.Where(it => it.Flag == '1')
|
||||
.ToListAsync()
|
||||
.GetAwaiter().GetResult()
|
||||
.Adapt<List<AspNetCoreRateLimit.IpRateLimitPolicy>>();
|
||||
await _ipPolicyStore.SeedAsync();
|
||||
var pol = await _ipPolicyStore.GetAsync(_options.IpPolicyPrefix);
|
||||
pol.IpRules.AddRange(ipRateLimitPolicies);
|
||||
await _ipPolicyStore.SetAsync(_options.IpPolicyPrefix, pol);
|
||||
}
|
||||
return SUCCESS(res);
|
||||
}
|
||||
|
||||
[HttpPatch("enableIpRateLimitPolicy/{id}")]
|
||||
public async Task<IActionResult> EnableIpRateLimitPolicy([FromRoute] long id)
|
||||
{
|
||||
var isEnable = await _ipRateLimitPolicyService
|
||||
.Queryable()
|
||||
.Where(it => it.Id == id
|
||||
&& it.Flag == '1')
|
||||
.AnyAsync();
|
||||
if (isEnable)
|
||||
{
|
||||
throw new CustomException("已启用,无法再次启用");
|
||||
}
|
||||
await _ipRateLimitPolicyService.Updateable(new IpRateLimitPolicy
|
||||
{
|
||||
Id = id,
|
||||
Flag = '1'
|
||||
}).UpdateColumns(it => it.Flag)
|
||||
.ExecuteCommandAsync();
|
||||
var ipRateLimitPolicy = await _ipRateLimitPolicyService.Queryable()
|
||||
.Includes(it => it.Rules.Where(r => r.Flag == '1').ToList())
|
||||
.Where(it => it.Id == id)
|
||||
.SingleAsync();
|
||||
var pol = await _ipPolicyStore.GetAsync(_options.IpPolicyPrefix);
|
||||
pol.IpRules.Add(ipRateLimitPolicy.Adapt<AspNetCoreRateLimit.IpRateLimitPolicy>());
|
||||
await _ipPolicyStore.SetAsync(_options.IpPolicyPrefix, pol);
|
||||
return SUCCESS('1');
|
||||
}
|
||||
|
||||
[HttpPatch("disableIpRateLimitPolicy/{id}")]
|
||||
public async Task<IActionResult> DisableIpRateLimitPolicy([FromRoute] long id)
|
||||
{
|
||||
var isEnable = await _ipRateLimitPolicyService
|
||||
.Queryable()
|
||||
.Where(it => it.Id == id
|
||||
&& it.Flag == '1')
|
||||
.AnyAsync();
|
||||
if (!isEnable)
|
||||
{
|
||||
throw new CustomException("已禁用,无法再次禁用");
|
||||
}
|
||||
await _ipRateLimitPolicyService.Updateable(new IpRateLimitPolicy
|
||||
{
|
||||
Id = id,
|
||||
Flag = '0'
|
||||
}).UpdateColumns(it => it.Flag)
|
||||
.ExecuteCommandAsync();
|
||||
var ipRateLimitPolicies = _ipRateLimitPolicyService.Queryable()
|
||||
.Includes(it => it.Rules.Where(r => r.Flag == '1').ToList())
|
||||
.Where(it => it.Flag == '1')
|
||||
.ToListAsync()
|
||||
.GetAwaiter().GetResult()
|
||||
.Adapt<List<AspNetCoreRateLimit.IpRateLimitPolicy>>();
|
||||
await _ipPolicyStore.RemoveAsync(_options.IpPolicyPrefix);
|
||||
await _ipPolicyStore.SeedAsync();
|
||||
var pol = await _ipPolicyStore.GetAsync(_options.IpPolicyPrefix);
|
||||
pol.IpRules.AddRange(ipRateLimitPolicies);
|
||||
await _ipPolicyStore.SetAsync(_options.IpPolicyPrefix, pol);
|
||||
return SUCCESS('0');
|
||||
}
|
||||
|
||||
[HttpDelete("deleteIpRateLimitPolicy/{id}")]
|
||||
public async Task DeleteIpRateLimitPolicyAsync([FromRoute] long id)
|
||||
{
|
||||
var isEnable = await _ipRateLimitPolicyService
|
||||
.Queryable()
|
||||
.Where(it => it.Id == id
|
||||
&& it.Flag == '1')
|
||||
.AnyAsync();
|
||||
await _ipRateLimitPolicyService
|
||||
.DeleteNav(it => it.Id == id)
|
||||
.Include(it => it.Rules)
|
||||
.ExecuteCommandAsync();
|
||||
if (isEnable)
|
||||
{
|
||||
var ipRateLimitPolicies = _ipRateLimitPolicyService.Queryable()
|
||||
.Includes(it => it.Rules.Where(r => r.Flag == '1').ToList())
|
||||
.Where(it => it.Flag == '1')
|
||||
.ToListAsync()
|
||||
.GetAwaiter().GetResult()
|
||||
.Adapt<List<AspNetCoreRateLimit.IpRateLimitPolicy>>();
|
||||
await _ipPolicyStore.RemoveAsync(_options.IpPolicyPrefix);
|
||||
await _ipPolicyStore.SeedAsync();
|
||||
var pol = await _ipPolicyStore.GetAsync(_options.IpPolicyPrefix);
|
||||
pol.IpRules.AddRange(ipRateLimitPolicies);
|
||||
await _ipPolicyStore.SetAsync(_options.IpPolicyPrefix, pol);
|
||||
}
|
||||
}
|
||||
|
||||
[HttpGet("getIpRateLimitLogPage")]
|
||||
public async Task<IActionResult> GetIpRateLimitLogPage([FromQuery] IpRateLimitLog ipRateLimitLog, PagerInfo pager)
|
||||
{
|
||||
return SUCCESS(await _ipRateLimitLogService.SelectIpRateLimitLogPageAsync(ipRateLimitLog, pager));
|
||||
}
|
||||
|
||||
[HttpGet("get")]
|
||||
public async Task<IpRateLimitPolicies> Get()
|
||||
{
|
||||
return await _ipPolicyStore.GetAsync(_options.IpPolicyPrefix);
|
||||
}
|
||||
|
||||
[HttpGet("checkIp/{ip}")]
|
||||
public async Task<IActionResult> CheckIp(string ip)
|
||||
{
|
||||
var res = await _ipRateLimitPolicyService.Queryable()
|
||||
.Where(it => it.Ip == ip)
|
||||
.AnyAsync();
|
||||
return SUCCESS(res);
|
||||
}
|
||||
}
|
||||
@ -2,6 +2,8 @@ using Infrastructure.Extensions;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Options;
|
||||
using System.Diagnostics;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace ZR.Admin.WebApi.Controllers.monitor
|
||||
@ -48,8 +50,12 @@ namespace ZR.Admin.WebApi.Controllers.monitor
|
||||
string appRAM = ((double)Process.GetCurrentProcess().WorkingSet64 / 1048576).ToString("N2") + " MB";
|
||||
string startTime = Process.GetCurrentProcess().StartTime.ToString("yyyy-MM-dd HH:mm:ss");
|
||||
string sysRunTime = ComputerHelper.GetRunTime();
|
||||
string serverIP = Request.HttpContext.Connection.LocalIpAddress.MapToIPv4().ToString() + ":" + Request.HttpContext.Connection.LocalPort;//获取服务器IP
|
||||
|
||||
// string serverIP = Request.HttpContext.Connection.LocalIpAddress.MapToIPv4().ToString() + ":" + Request.HttpContext.Connection.LocalPort;//获取服务器IP
|
||||
var host = Dns.GetHostEntry(Dns.GetHostName());
|
||||
var ip = host.AddressList
|
||||
.FirstOrDefault(it => it.AddressFamily == AddressFamily.InterNetwork);
|
||||
var serverIP = ip + ":" + Request.HttpContext.Connection.LocalPort;//获取服务器IP
|
||||
|
||||
var programStartTime = Process.GetCurrentProcess().StartTime;
|
||||
string programRunTime = DateTimeHelper.FormatTime((DateTime.Now - programStartTime).TotalMilliseconds.ToString().Split('.')[0].ParseToLong());
|
||||
var data = new
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using ZR.Admin.WebApi.Filters;
|
||||
using ZR.Model.System.Dto;
|
||||
using ZR.Service.System.IService;
|
||||
using ZR.ServiceCore.Model.Dto;
|
||||
|
||||
//创建时间:2023-08-17
|
||||
namespace ZR.Admin.WebApi.Controllers
|
||||
|
||||
@ -5,6 +5,7 @@ using ZR.Admin.WebApi.Filters;
|
||||
using ZR.Model;
|
||||
using ZR.Model.System;
|
||||
using ZR.Service.System.IService;
|
||||
using ZR.ServiceCore.Model;
|
||||
|
||||
namespace ZR.Admin.WebApi.Controllers.monitor
|
||||
{
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using ZR.Admin.WebApi.Extensions;
|
||||
using ZR.Admin.WebApi.Filters;
|
||||
using ZR.Model.System.Dto;
|
||||
using ZR.Service.System.IService;
|
||||
using ZR.ServiceCore.Model.Dto;
|
||||
|
||||
namespace ZR.Admin.WebApi.Controllers.monitor
|
||||
{
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
using Microsoft.AspNetCore.SignalR;
|
||||
using ZR.Admin.WebApi.Filters;
|
||||
using ZR.Model;
|
||||
using ZR.Model.System.Dto;
|
||||
using ZR.ServiceCore.Model.Dto;
|
||||
using ZR.ServiceCore.Signalr;
|
||||
|
||||
namespace ZR.Admin.WebApi.Controllers.monitor
|
||||
@ -30,11 +30,11 @@ namespace ZR.Admin.WebApi.Controllers.monitor
|
||||
[HttpGet("list")]
|
||||
public IActionResult Index([FromQuery] PagerInfo parm)
|
||||
{
|
||||
var result = MessageHub.onlineClients
|
||||
var result = MessageHub.OnlineClients
|
||||
.OrderByDescending(f => f.LoginTime)
|
||||
.Skip(parm.PageNum - 1).Take(parm.PageSize);
|
||||
|
||||
return SUCCESS(new { result, totalNum = MessageHub.onlineClients.Count });
|
||||
return SUCCESS(new { result, totalNum = MessageHub.OnlineClients.Count });
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@ -1,21 +1,34 @@
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:5.0 AS base
|
||||
#创建 /app文件夹
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:7.0 AS base
|
||||
WORKDIR /app
|
||||
#创建挂载目录,用于将程序部署在服务器本地
|
||||
#VOLUME /app
|
||||
#设置docker容器对外暴露端口
|
||||
EXPOSE 8888
|
||||
VOLUME /app/logs
|
||||
#COPY bin/Release/net5.0/publish/ app/
|
||||
COPY . app/
|
||||
#EXPOSE 443
|
||||
VOLUME /app/adminlogs
|
||||
VOLUME /app/wwwroot
|
||||
|
||||
#设置容器内的时区,如果不设置,默认时区是标准时间比北京时间晚8个小时
|
||||
RUN echo "Asia/shanghai" > /etc/timezone
|
||||
RUN cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
|
||||
FROM mcr.microsoft.com/dotnet/sdk:7.0 AS build
|
||||
WORKDIR /src
|
||||
COPY ["ZR.Admin.WebApi/ZR.Admin.WebApi.csproj", "ZR.Admin.WebApi/"]
|
||||
COPY ["ZR.CodeGenerator/ZR.CodeGenerator.csproj", "ZR.CodeGenerator/"]
|
||||
COPY ["Infrastructure/ZR.Infrastructure.csproj", "Infrastructure/"]
|
||||
COPY ["ZR.Common/ZR.Common.csproj", "ZR.Common/"]
|
||||
COPY ["ZR.ServiceCore/ZR.ServiceCore.csproj", "ZR.ServiceCore/"]
|
||||
COPY ["ZR.Repository/ZR.Repository.csproj", "ZR.Repository/"]
|
||||
COPY ["ZR.Model/ZR.Model.csproj", "ZR.Model/"]
|
||||
COPY ["ZR.Service/ZR.Service.csproj", "ZR.Service/"]
|
||||
COPY ["ZR.Tasks/ZR.Tasks.csproj", "ZR.Tasks/"]
|
||||
COPY ["ZR.Admin.Grpc/ZR.Admin.Grpc.csproj", "ZR.Admin.Grpc/"]
|
||||
RUN dotnet restore "ZR.Admin.WebApi/ZR.Admin.WebApi.csproj"
|
||||
COPY . .
|
||||
WORKDIR "/src/ZR.Admin.WebApi"
|
||||
RUN dotnet build "ZR.Admin.WebApi.csproj" -c Release -o /app/build
|
||||
|
||||
# 复制发布文件到工作目录
|
||||
#COPY . app/
|
||||
FROM build AS publish
|
||||
RUN dotnet publish "ZR.Admin.WebApi.csproj" -c Release -o /app/publish /p:UseAppHost=false
|
||||
|
||||
FROM base AS final
|
||||
WORKDIR /app
|
||||
|
||||
#等价于 dotnet ZR.Admin.WebApi.dll,如果不指定启动端口默认在docker里面启动端口是80端口
|
||||
ENTRYPOINT ["dotnet", "ZR.Admin.WebApi.dll", "--server.urls","http://*:8888"]
|
||||
COPY --from=publish /app/publish .
|
||||
ENTRYPOINT ["dotnet", "ZR.Admin.WebApi.dll"]
|
||||
ENV TZ=Asia/Shanghai
|
||||
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
|
||||
RUN apt-get update && apt-get install -y libfontconfig1
|
||||
@ -1,6 +1,7 @@
|
||||
using Quartz.Spi;
|
||||
using SqlSugar.IOC;
|
||||
using ZR.Model.System;
|
||||
using ZR.ServiceCore.Model;
|
||||
using ZR.Tasks;
|
||||
|
||||
namespace ZR.Admin.WebApi.Extensions
|
||||
|
||||
@ -7,4 +7,5 @@ global using Infrastructure.Model;
|
||||
global using Mapster;
|
||||
global using Infrastructure.Extensions;
|
||||
global using Infrastructure.Controllers;
|
||||
global using ZR.ServiceCore.Middleware;
|
||||
global using ZR.ServiceCore.Middleware;
|
||||
global using Microsoft.AspNetCore.Mvc;
|
||||
47
ZR.Admin.WebApi/IpRateLimitConfig.json
Normal file
47
ZR.Admin.WebApi/IpRateLimitConfig.json
Normal file
@ -0,0 +1,47 @@
|
||||
{
|
||||
//接口请求限制
|
||||
"IpRateLimiting": {
|
||||
"EnableEndpointRateLimiting": true,
|
||||
"StackBlockedRequests": false,
|
||||
"RealIpHeader": "X-Real-IP",
|
||||
"ClientIdHeader": "X-ClientId",
|
||||
"HttpStatusCode": 429,
|
||||
"EndpointWhitelist": [
|
||||
"post:/system/dict/data/types",
|
||||
"*:/msghub/negotiate",
|
||||
"*:/LogOut",
|
||||
"*:/common/uploadfile",
|
||||
"post:/aim/msg/list/sendmsg"
|
||||
],
|
||||
"QuotaExceededResponse": {
|
||||
"Content": "{{\"code\":429,\"msg\":\"访问过于频繁,请稍后重试\"}}",
|
||||
"ContentType": "application/json",
|
||||
"StatusCode": 429
|
||||
},
|
||||
// "IpWhitelist": [ "127.0.0.1", "::1/10", "192.168.0.0/24" ],
|
||||
//通用规则,api规则,结尾一定要带*
|
||||
"GeneralRules": [
|
||||
{
|
||||
"Endpoint": "*:/captchaImage",
|
||||
//时间段,格式:{数字}{单位};可使用单位:s, m, h, d
|
||||
"Period": "3s",
|
||||
"Limit": 5
|
||||
},
|
||||
{
|
||||
"Endpoint": "((post)|(put)):*",
|
||||
"Period": "3s",
|
||||
"Limit": 1
|
||||
},
|
||||
{
|
||||
"Endpoint": "*:/aim/msg/list/SendMsg",
|
||||
"Period": "1s",
|
||||
"Limit": 0,
|
||||
}
|
||||
]
|
||||
},
|
||||
"IpRateLimitPolicies": {
|
||||
//ip规则
|
||||
"IpRules": [
|
||||
]
|
||||
}
|
||||
}
|
||||
@ -1,10 +1,11 @@
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
|
||||
autoReload="true"
|
||||
internalLogLevel="Info"
|
||||
internalLogFile="nlog-internal.log">
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
|
||||
autoReload="true"
|
||||
internalLogLevel="Info"
|
||||
internalLogFile="nlog-internal.log"
|
||||
throwConfigExceptions="true">
|
||||
|
||||
<!--Nlog 文档参考地址:https://github.com/NLog/NLog/wiki/Getting-started-with-ASP.NET-Core-2-->
|
||||
<!--internalLogLevel Nlog内部日志记录为Off关闭。除非纠错,不可以设为Trace否则速度很慢,起码Debug以上-->
|
||||
@ -45,14 +46,14 @@
|
||||
|
||||
<!--SQL文件-->
|
||||
<target name="sqlfile" xsi:type="File"
|
||||
fileName="${basedir}/adminlogs/sql.txt"
|
||||
archiveFileName="${basedir}/adminlogs/bak/sql/sql{###}.txt"
|
||||
archiveEvery="Day"
|
||||
archiveNumbering="DateAndSequence"
|
||||
archiveAboveSize="20000000"
|
||||
maxArchiveFiles="30"
|
||||
keepFileOpen="false"
|
||||
layout="${longdate} | ${uppercase:${level}} | ${aspnet-request-iP} | ${aspnet-request-headers:HeaderNames=userName} | ${aspnet-request-url} ${newline}${message}"/>
|
||||
fileName="${basedir}/adminlogs/sql.txt"
|
||||
archiveFileName="${basedir}/adminlogs/bak/sql/sql.{###}.txt"
|
||||
archiveEvery="Day"
|
||||
archiveNumbering="DateAndSequence"
|
||||
archiveAboveSize="20000000"
|
||||
maxArchiveFiles="30"
|
||||
keepFileOpen="false"
|
||||
layout="${longdate} | ${uppercase:${level}} | ${aspnet-request-iP} | ${aspnet-request-headers:HeaderNames=userName} | ${aspnet-request-url} ${newline}${message}"/>
|
||||
|
||||
<!--写入彩色控制台-->
|
||||
<target name="consoleSql" xsi:type="ColoredConsole" useDefaultRowHighlightingRules="false"
|
||||
@ -67,8 +68,34 @@
|
||||
<highlight-word regex="】" foregroundColor="Blue" />
|
||||
</target>
|
||||
|
||||
<!--日志打印到控制台-->
|
||||
<target name="console" xsi:type="ColoredConsole"
|
||||
layout="${date:format=MM-dd HH\:mm\:ss} | ${aspnet-request-url} ${newline} ${message}">
|
||||
<highlight-row condition="level == LogLevel.Debug" foregroundColor="DarkGray" />
|
||||
<highlight-row condition="level == LogLevel.Info" foregroundColor="Gray" />
|
||||
<highlight-row condition="level == LogLevel.Warn" foregroundColor="Yellow" />
|
||||
<highlight-row condition="level == LogLevel.Error" foregroundColor="Red" />
|
||||
<highlight-row condition="level == LogLevel.Fatal" foregroundColor="Red" backgroundColor="White" />
|
||||
</target>
|
||||
|
||||
<!--写入黑洞-->
|
||||
<target name="blackhole" xsi:type="Null" />
|
||||
|
||||
<target name="ipRateLimitFile" xsi:type="File"
|
||||
fileName="${basedir}/adminlogs/ipratelimit.txt"
|
||||
archiveFileName="${basedir}/adminlogs/bak/ipratelimit/ipratelimit{###}.txt"
|
||||
archiveEvery="Day"
|
||||
archiveNumbering="DateAndSequence"
|
||||
archiveAboveSize="20000000"
|
||||
maxArchiveFiles="30"
|
||||
keepFileOpen="false"
|
||||
layout="${date:format=MM-dd HH\:mm\:ss} | ${aspnet-request-url} ${newline} ${message}"
|
||||
/>
|
||||
<!-- 速率限制日志写入控制台 -->
|
||||
<target name="consoleIpRateLimit" xsi:type="ColoredConsole" useDefaultRowHighlightingRules="false"
|
||||
layout="${date:format=MM-dd HH\:mm\:ss} | ${aspnet-request-url} ${newline} ${message}">
|
||||
<highlight-row condition="level == LogLevel.Info" foregroundColor="Blue" />
|
||||
</target>
|
||||
</targets>
|
||||
|
||||
<rules>
|
||||
@ -79,10 +106,10 @@
|
||||
<!--<logger name="System.*" writeTo="blackhole" final="true" />-->
|
||||
<!-- Quartz -->
|
||||
<logger name="Quartz*" minlevel="Trace" maxlevel="Info" final="true" />
|
||||
<logger name="*.SqlSugar.SqlsugarSetup" final="true" writeTo="consoleSql,sqlfile"/>
|
||||
<logger name="*" minLevel="Trace" writeTo="allfile" />
|
||||
<logger name="*.SqlSugar.SqlSugarSetup" final="true" writeTo="consoleSql,sqlfile"/>
|
||||
<logger name="*" minLevel="Trace" writeTo="allfile,console" />
|
||||
<logger name="*.GlobalExceptionMiddleware" final="true" writeTo="consoleSql,errorfile"/>
|
||||
|
||||
<logger name="ZR.Admin.WebApi.Middleware.CustomIpRateLimitMiddleware" final="true" writeTo="consoleIpRateLimit,ipRateLimitFile" />
|
||||
<!--Skip non-critical Microsoft logs and so log only own logs-->
|
||||
<logger name="Microsoft.*,Quartz.Core.QuartzSchedulerThread" maxlevel="Info" final="true" />
|
||||
</rules>
|
||||
|
||||
@ -1,16 +1,31 @@
|
||||
using AspNetCoreRateLimit;
|
||||
using Infrastructure.Converter;
|
||||
using Microsoft.AspNetCore.DataProtection;
|
||||
using Microsoft.AspNetCore.RateLimiting;
|
||||
using Microsoft.AspNetCore.Server.Kestrel.Core;
|
||||
using Microsoft.Extensions.Caching.Distributed;
|
||||
using Microsoft.Extensions.Caching.Redis;
|
||||
using Microsoft.Extensions.Options;
|
||||
using NLog.Web;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using ZR.Admin.Grpc;
|
||||
using ZR.Admin.Grpc.Services;
|
||||
using ZR.Admin.WebApi.Extensions;
|
||||
using ZR.Common.Cache;
|
||||
using ZR.Infrastructure.Cache;
|
||||
using ZR.Infrastructure.WebExtensions;
|
||||
using ZR.ServiceCore.Services.IService;
|
||||
using ZR.ServiceCore.Signalr;
|
||||
using ZR.ServiceCore.SqlSugar;
|
||||
using IpRateLimitPolicy = AspNetCoreRateLimit.IpRateLimitPolicy;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
//load json config by ipRateLimit
|
||||
builder.Configuration.AddJsonFile("IpRateLimitConfig.json", true, true);
|
||||
|
||||
//load json config by loginVerify
|
||||
builder.Configuration.AddJsonFile("loginVerifyConf.json", true, true);
|
||||
|
||||
// NLog: Setup NLog for Dependency injection
|
||||
//builder.Logging.ClearProviders();
|
||||
builder.Host.UseNLog();
|
||||
@ -24,6 +39,8 @@ builder.Services.AddSwaggerGen();
|
||||
builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
|
||||
// 跨域配置
|
||||
builder.Services.AddCors(builder.Configuration);
|
||||
// Grpc
|
||||
builder.Services.AddGrpc();
|
||||
// 显示logo
|
||||
builder.Services.AddLogo();
|
||||
//消除Error unprotecting the session cookie警告
|
||||
@ -52,8 +69,15 @@ var openRedis = builder.Configuration["RedisServer:open"];
|
||||
if (openRedis == "1")
|
||||
{
|
||||
RedisServer.Initalize();
|
||||
builder.Services.AddSingleton<IDistributedCache>(new CSRedisCache(RedisHelper.Instance));
|
||||
}
|
||||
|
||||
builder.Services.AddRateLimiter(o => o
|
||||
.AddFixedWindowLimiter(policyName: "fixed", options =>
|
||||
{
|
||||
// configuration
|
||||
}));
|
||||
|
||||
builder.Services.AddMvc(options =>
|
||||
{
|
||||
options.Filters.Add(typeof(GlobalActionMonitor));//全局注册
|
||||
@ -76,6 +100,26 @@ builder.Services.AddSignalR()
|
||||
options.PayloadSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
|
||||
});
|
||||
builder.Services.AddSwaggerConfig();
|
||||
//using var channel = GrpcChannel.ForAddress("https://localhost:7025");
|
||||
//var client = new Greeter.GreeterClient(channel);
|
||||
//var reply = await client.SayHelloAsync(new HelloRequest { Name = "GreeterClient" });
|
||||
//Console.WriteLine("Greeting: " + reply.Message);
|
||||
//
|
||||
// var blockClient = new Block.BlockClient(channel);
|
||||
// var blockReply = await blockClient.GetBlockAsync(new BlockRequest { In = "asads" });
|
||||
// Console.WriteLine("BlockReply: " + blockReply.Out);
|
||||
//builder.Services.AddGrpcServiceConfiguration(builder.Configuration);
|
||||
|
||||
// 配置 Kestrel 监听 HTTP/2 的非加密流量
|
||||
//builder.WebHost.ConfigureKestrel(options =>
|
||||
//{
|
||||
// // 如果你只想监听一个端口,只保留其中一个 Listen
|
||||
// options.ListenLocalhost(8888, o =>
|
||||
// {
|
||||
// o.Protocols = HttpProtocols.Http2; // 明确设置为 Http2
|
||||
// });
|
||||
|
||||
//});
|
||||
|
||||
var app = builder.Build();
|
||||
InternalApp.ServiceProvider = app.Services;
|
||||
@ -109,7 +153,7 @@ app.UseStaticFiles();
|
||||
//开启路由访问
|
||||
app.UseRouting();
|
||||
app.UseCors("Policy");//要放在app.UseEndpoints前。
|
||||
//app.UseHttpsRedirection();
|
||||
app.UseHttpsRedirection();
|
||||
|
||||
app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
@ -124,7 +168,8 @@ if (builder.Environment.IsProduction())
|
||||
//使用swagger
|
||||
app.UseSwagger();
|
||||
//启用客户端IP限制速率
|
||||
app.UseIpRateLimiting();
|
||||
// app.UseIpRateLimiting();
|
||||
app.UseMiddleware<CustomIpRateLimitMiddleware>();
|
||||
app.UseRateLimiter();
|
||||
//设置socket连接
|
||||
app.MapHub<MessageHub>("/msgHub");
|
||||
@ -134,4 +179,36 @@ app.MapControllerRoute(
|
||||
pattern: "{controller=Home}/{action=Index}/{id?}");
|
||||
|
||||
app.MapControllers();
|
||||
|
||||
using (var serviceScope = app.Services.CreateScope())
|
||||
{
|
||||
var services = serviceScope.ServiceProvider;
|
||||
|
||||
// get the IpPolicyStore instance
|
||||
var ipPolicyStore = services.GetRequiredService<IIpPolicyStore>();
|
||||
|
||||
// seed IP data from appsettings
|
||||
ipPolicyStore.SeedAsync().GetAwaiter().GetResult();
|
||||
|
||||
var optionsAccessor = services.GetRequiredService<IOptions<IpRateLimitOptions>>();
|
||||
var ipRateLimitPolicyService = services.GetRequiredService<IIpRateLimitPolicyService>();
|
||||
var ipRateLimitPolicies = ipRateLimitPolicyService.Queryable()
|
||||
.Includes(it => it.Rules.Where(r => r.Flag == '1').ToList())
|
||||
.Where(it => it.Flag == '1')
|
||||
.ToListAsync().GetAwaiter().GetResult();
|
||||
var pol = await ipPolicyStore.GetAsync(optionsAccessor.Value.IpPolicyPrefix);
|
||||
pol.IpRules.AddRange(ipRateLimitPolicies.Adapt<List<IpRateLimitPolicy>>());
|
||||
await ipPolicyStore.SetAsync(optionsAccessor.Value.IpPolicyPrefix, pol);
|
||||
|
||||
//var greeterClient = services.GetRequiredService<Greeter.GreeterClient>();
|
||||
//var helloReply = await greeterClient.SayHelloAsync(new HelloRequest
|
||||
//{
|
||||
// Name = "gree"
|
||||
//});
|
||||
//Console.WriteLine(helloReply);
|
||||
}
|
||||
|
||||
app.MapGrpcService<GreeterService>();
|
||||
app.MapGrpcService<MyDiaryService>();
|
||||
|
||||
app.Run();
|
||||
@ -10,13 +10,13 @@
|
||||
},
|
||||
"profiles": {
|
||||
"ZR.Admin.WebApi": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchUrl": "",
|
||||
"applicationUrl": "http://localhost:8888",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchUrl": "",
|
||||
"applicationUrl": "https://localhost:8888",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,15 +1,17 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net7.0</TargetFramework>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<GenerateDocumentationFile>true</GenerateDocumentationFile>
|
||||
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
|
||||
<NoWarn>1701;1702;1591,8603,8602,8604,8600,8618</NoWarn>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\ZR.Admin.Grpc\ZR.Admin.Grpc.csproj" />
|
||||
<ProjectReference Include="..\ZR.CodeGenerator\ZR.CodeGenerator.csproj" />
|
||||
<ProjectReference Include="..\ZR.Service\ZR.Service.csproj" />
|
||||
<ProjectReference Include="..\ZR.Tasks\ZR.Tasks.csproj" />
|
||||
@ -28,6 +30,9 @@
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Content Include="..\.dockerignore">
|
||||
<Link>.dockerignore</Link>
|
||||
</Content>
|
||||
<None Update="ip2region.db">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
@ -37,5 +42,8 @@
|
||||
<Content Update="wwwroot\export\**\*">
|
||||
<CopyToPublishDirectory>Never</CopyToPublishDirectory>
|
||||
</Content>
|
||||
<Content Update="appsettings.Production.json">
|
||||
<DependentUpon>appsettings.json</DependentUpon>
|
||||
</Content>
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
|
||||
20
ZR.Admin.WebApi/appsettings.Production.json
Normal file
20
ZR.Admin.WebApi/appsettings.Production.json
Normal file
@ -0,0 +1,20 @@
|
||||
{
|
||||
"urls": "http://[*]:8888", //项目启动url,如果改动端口前端对应devServer也需要进行修改
|
||||
"dbConfigs": [
|
||||
{
|
||||
"Conn": "server=8.140.174.251;user=admin;pwd=admin123;database=ZrAdmin",
|
||||
"DbType": 0, //数据库类型 MySql = 0, SqlServer = 1, Oracle = 3,PgSql = 4
|
||||
"ConfigId": "0", //多租户唯一标识
|
||||
"IsAutoCloseConnection": true
|
||||
}
|
||||
//...下面添加更多的数据库源
|
||||
],
|
||||
//redis服务配置
|
||||
"RedisServer": {
|
||||
"open": 1, //是否启用redis
|
||||
"Cache": "8.140.174.251:6379,password=Wyd210213,defaultDatabase=0,poolsize=50,ssl=false,writeBuffer=10240,prefix=cache:",
|
||||
// "Cache": "127.0.0.1:6379,password=Wyd210213,defaultDatabase=0,poolsize=50,ssl=false,writeBuffer=10240,prefix=cache:",
|
||||
"Session": "8.140.174.251:6379,password=Wyd210213,defaultDatabase=0,poolsize=50,ssl=false,writeBuffer=10240,prefix=session:"
|
||||
// "Session": "127.0.0.1:6379,password=Wyd210213,defaultDatabase=0,poolsize=50,ssl=false,writeBuffer=10240,prefix=session:"
|
||||
},
|
||||
}
|
||||
@ -1,140 +1,126 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft": "Warning",
|
||||
"Microsoft.Hosting.Lifetime": "Information"
|
||||
}
|
||||
},
|
||||
"dbConfigs": [
|
||||
{
|
||||
"Conn": "Data Source=LAPTOP-STKF2M8H\\SQLEXPRESS;User ID=admin;Password=admin123;Initial Catalog=ZrAdmin;",
|
||||
"DbType": 1, //数据库类型 MySql = 0, SqlServer = 1, Oracle = 3,PgSql = 4
|
||||
"ConfigId": "0", //多租户唯一标识
|
||||
"IsAutoCloseConnection": true
|
||||
}
|
||||
//...下面添加更多的数据库源
|
||||
],
|
||||
//代码生成数据库配置
|
||||
"CodeGenDbConfig": {
|
||||
//代码生成连接字符串,注意{dbName}为固定格式,不要填写数据库名
|
||||
"Conn": "Data Source=LAPTOP-STKF2M8H\\SQLEXPRESS;User ID=admin;Password=admin123;Initial Catalog={dbName};",
|
||||
"DbType": 1,
|
||||
"IsAutoCloseConnection": true,
|
||||
"DbName": "ZrAdmin" //代码生成默认连接数据库,Oracle库是实例的名称
|
||||
},
|
||||
"urls": "http://localhost:8888", //项目启动url,如果改动端口前端对应devServer也需要进行修改
|
||||
"corsUrls": [ "http://localhost:8887", "http://localhost:8886" ], //跨域地址(前端启动项目,前后端分离单独部署需要设置),多个用","隔开
|
||||
"JwtSettings": {
|
||||
"Issuer": "ZRAdmin.NET", //即token的签发者。
|
||||
"Audience": "ZRAdmin.NET", //指该token是服务于哪个群体的(群体范围)
|
||||
"SecretKey": "SecretKey-ZRADMIN.NET-20210101",
|
||||
"Expire": 1440, //jwt登录过期时间(分)
|
||||
"RefreshTokenTime": 5,//分钟
|
||||
"TokenType": "Bearer"
|
||||
},
|
||||
"InjectClass": [ "ZR.Repository", "ZR.Service", "ZR.Tasks", "ZR.ServiceCore" ], //自动注入类
|
||||
"ShowDbLog": true, //是否打印db日志
|
||||
"InitDb": false, //是否初始化db
|
||||
"DemoMode": false, //是否演示模式
|
||||
"SingleLogin": false,//是否单点登录
|
||||
"Upload": {
|
||||
"uploadUrl": "http://localhost:8888", //本地存储资源访问路径
|
||||
"localSavePath": "", //本地上传默认文件存储目录 wwwroot
|
||||
"maxSize": 15, //上传文件大小限制 15M
|
||||
"notAllowedExt": [ ".bat", ".exe", ".jar", ".js" ]
|
||||
},
|
||||
//阿里云存储配置
|
||||
"ALIYUN_OSS": {
|
||||
"REGIONID": "", //eg:cn-hangzhou
|
||||
"KEY": "XX",
|
||||
"SECRET": "XX",
|
||||
"bucketName": "bucketName",
|
||||
"domainUrl": "http://xxx.xxx.com", //访问资源域名
|
||||
"maxSize": 100 //上传文件大小限制 100M
|
||||
},
|
||||
//企业微信通知配置
|
||||
"WxCorp": {
|
||||
"AgentID": "",
|
||||
"CorpID": "",
|
||||
"CorpSecret": "",
|
||||
"SendUser": "@all"
|
||||
},
|
||||
//微信公众号设置
|
||||
"WxOpen": {
|
||||
"AppID": "",
|
||||
"AppSecret": ""
|
||||
},
|
||||
//代码生成配置
|
||||
"gen": {
|
||||
//是否显示移动端代码生成
|
||||
"showApp": false,
|
||||
//自动去除表前缀
|
||||
"autoPre": true,
|
||||
"author": "admin",
|
||||
"tablePrefix": "sys_", //"表前缀(生成类名不会包含表前缀,多个用逗号分隔)",
|
||||
"vuePath": "", //前端代码存储路径eg:D:\Work\ZRAdmin-Vue3
|
||||
"csharpTypeArr": {
|
||||
"string": [ "varchar", "nvarchar", "text", "longtext" ],
|
||||
"int": [ "int", "integer", "smallint", "int4", "int8", "int2" ],
|
||||
"long": [ "bigint", "number" ],
|
||||
"float": [ "numeric", "real", "float" ],
|
||||
"decimal": [ "money", "decimal", "smallmoney" ],
|
||||
"dateTime": [ "date", "datetime", "datetime2", "smalldatetime", "timestamp" ],
|
||||
"byte": [ "tinyint" ],
|
||||
"bool": [ "bit" ]
|
||||
}
|
||||
},
|
||||
//邮箱配置信息
|
||||
"MailOptions": {
|
||||
//发件人名称
|
||||
"FromName": "system",
|
||||
//发送人邮箱
|
||||
"FromEmail": "", //eg:xxxx@qq.com
|
||||
//发送人邮箱密码
|
||||
"Password": "",
|
||||
//协议
|
||||
"Smtp": "smtp.qq.com",
|
||||
"Port": 587,
|
||||
"Signature": "系统邮件,请勿回复!",
|
||||
"UseSsl": true
|
||||
},
|
||||
//redis服务配置
|
||||
"RedisServer": {
|
||||
"open": 0, //是否启用redis
|
||||
"Cache": "127.0.0.1:6379,defaultDatabase=0,poolsize=50,ssl=false,writeBuffer=10240,prefix=cache:",
|
||||
"Session": "127.0.0.1:6379,defaultDatabase=0,poolsize=50,ssl=false,writeBuffer=10240,prefix=session:"
|
||||
},
|
||||
//接口请求限制
|
||||
"IpRateLimiting": {
|
||||
"EnableEndpointRateLimiting": true,
|
||||
"StackBlockedRequests": false,
|
||||
"RealIpHeader": "X-Real-IP",
|
||||
"ClientIdHeader": "X-ClientId",
|
||||
"HttpStatusCode": 429,
|
||||
"EndpointWhitelist": [ "post:/system/dict/data/types", "*:/msghub/negotiate", "*:/LogOut", "*:/common/uploadfile", "*:/VerifyScan" ],
|
||||
"QuotaExceededResponse": {
|
||||
"Content": "{{\"code\":429,\"msg\":\"访问过于频繁,请稍后重试\"}}",
|
||||
"ContentType": "application/json",
|
||||
"StatusCode": 429
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft": "Warning",
|
||||
"Microsoft.Hosting.Lifetime": "Information"
|
||||
}
|
||||
},
|
||||
//通用规则,api规则,结尾一定要带*
|
||||
"GeneralRules": [
|
||||
{
|
||||
"Endpoint": "*:/captchaImage",
|
||||
//时间段,格式:{数字}{单位};可使用单位:s, m, h, d
|
||||
"Period": "3s",
|
||||
"Limit": 5
|
||||
},
|
||||
{
|
||||
"Endpoint": "((post)|(put)):*",
|
||||
"Period": "3s",
|
||||
"Limit": 1
|
||||
}
|
||||
]
|
||||
},
|
||||
//验证码配置
|
||||
"CaptchaOptions": {
|
||||
"IgnoreCase": true // 比较时是否忽略大小写
|
||||
}
|
||||
"dbConfigs": [
|
||||
{
|
||||
"Conn": "server=127.0.0.1;user=admin;pwd=admin123;database=ZrAdmin;port=3306",
|
||||
"DbType": 0, //数据库类型 MySql = 0, SqlServer = 1, Oracle = 3,PgSql = 4
|
||||
"ConfigId": "0", //多租户唯一标识
|
||||
"IsAutoCloseConnection": true
|
||||
}
|
||||
//...下面添加更多的数据库源
|
||||
],
|
||||
//代码生成数据库配置
|
||||
"CodeGenDbConfig": {
|
||||
//代码生成连接字符串,注意{dbName}为固定格式,不要填写数据库名
|
||||
"Conn": "Data Source=127.0.0.1;user=admin;pwd=admin123;database=ZrAdmin;port=3306",
|
||||
"DbType": 0,
|
||||
"IsAutoCloseConnection": true,
|
||||
"DbName": "ZrAdmin" //代码生成默认连接数据库,Oracle库是实例的名称
|
||||
},
|
||||
"urls": "https://localhost:8888", //项目启动url,如果改动端口前端对应devServer也需要进行修改
|
||||
"corsUrls": [ "http://localhost:8887", "http://localhost:8886" ], //跨域地址(前端启动项目,前后端分离单独部署需要设置),多个用","隔开
|
||||
"JwtSettings": {
|
||||
"Issuer": "ZRAdmin.NET", //即token的签发者。
|
||||
"Audience": "ZRAdmin.NET", //指该token是服务于哪个群体的(群体范围)
|
||||
"SecretKey": "SecretKey-ZRADMIN.NET-20210101",
|
||||
"Expire": 1440, //jwt登录过期时间(分)
|
||||
"RefreshTokenTime": 5, //分钟
|
||||
"TokenType": "Bearer"
|
||||
},
|
||||
"InjectClass": [ "ZR.Repository", "ZR.Service", "ZR.Tasks", "ZR.ServiceCore" ], //自动注入类
|
||||
"ShowDbLog": true, //是否打印db日志
|
||||
"InitDb": false, //是否初始化db
|
||||
"DemoMode": false, //是否演示模式
|
||||
"SingleLogin": false, //是否单点登录
|
||||
"Upload": {
|
||||
"uploadUrl": "http://localhost:8888", //本地存储资源访问路径
|
||||
"localSavePath": "", //本地上传默认文件存储目录 wwwroot
|
||||
"maxSize": 15, //上传文件大小限制 15M
|
||||
"notAllowedExt": [ ".bat", ".exe", ".jar", ".js" ]
|
||||
},
|
||||
//阿里云存储配置
|
||||
"ALIYUN_OSS": {
|
||||
"REGIONID": "oss-cn-hangzhou.aliyuncs.com", //eg:cn-hangzhou
|
||||
"KEY": "LTAI5tBjDZatWWunAhxLAAFR",
|
||||
"SECRET": "Klcm77KdpkIROAl2ffPemK5I1yDshM",
|
||||
"bucketName": "markdownhexo",
|
||||
"domainUrl": "https://markdownhexo.oss-cn-hangzhou.aliyuncs.com", //访问资源域名
|
||||
"maxSize": 1000 //上传文件大小限制 1000M
|
||||
},
|
||||
//企业微信通知配置
|
||||
"WxCorp": {
|
||||
"AgentID": "",
|
||||
"CorpID": "",
|
||||
"CorpSecret": "",
|
||||
"SendUser": "@all"
|
||||
},
|
||||
//微信公众号设置
|
||||
"WxOpen": {
|
||||
"AppID": "",
|
||||
"AppSecret": ""
|
||||
},
|
||||
//代码生成配置
|
||||
"gen": {
|
||||
//是否显示移动端代码生成
|
||||
"showApp": false,
|
||||
//自动去除表前缀
|
||||
"autoPre": true,
|
||||
"author": "admin",
|
||||
"tablePrefix": "sys_", //"表前缀(生成类名不会包含表前缀,多个用逗号分隔)",
|
||||
"vuePath": "", //前端代码存储路径eg:D:\Work\ZRAdmin-Vue3
|
||||
"csharpTypeArr": {
|
||||
"string": [ "varchar", "nvarchar", "text", "longtext" ],
|
||||
"int": [ "int", "integer", "smallint", "int4", "int8", "int2" ],
|
||||
"long": [ "bigint", "number" ],
|
||||
"float": [ "numeric", "real", "float" ],
|
||||
"decimal": [ "money", "decimal", "smallmoney" ],
|
||||
"dateTime": [ "date", "datetime", "datetime2", "smalldatetime", "timestamp" ],
|
||||
"byte": [ "tinyint" ],
|
||||
"bool": [ "bit" ]
|
||||
}
|
||||
},
|
||||
//邮箱配置信息
|
||||
"MailOptions": {
|
||||
//发件人名称
|
||||
"FromName": "文永达",
|
||||
//发送人邮箱
|
||||
"FromEmail": "1224169330@qq.com", //eg:xxxx@qq.com
|
||||
//发送人邮箱密码
|
||||
"Password": "wbctsfvdazchibdh",
|
||||
//协议
|
||||
"Smtp": "smtp.qq.com",
|
||||
"Port": 465,
|
||||
"Signature": "系统邮件,请勿回复!",
|
||||
"UseSsl": true
|
||||
},
|
||||
//redis服务配置
|
||||
"RedisServer": {
|
||||
"open": 1, //是否启用redis
|
||||
"Cache": "127.0.0.1:6379,defaultDatabase=0,poolsize=50,ssl=false,writeBuffer=10240,prefix=cache:",
|
||||
"Session": "127.0.0.1:6379,defaultDatabase=0,poolsize=50,ssl=false,writeBuffer=10240,prefix=session:"
|
||||
},
|
||||
//验证码配置
|
||||
"CaptchaOptions": {
|
||||
"CaptchaType": 10,
|
||||
"IgnoreCase": true, // 比较时是否忽略大小写
|
||||
"ImageOption": {
|
||||
"FontSize": 36, // 字体大小
|
||||
"Animation": true, // 是否启用动画
|
||||
"TextBold": true, // 是否启用粗体
|
||||
"InterferenceLineCount": 4, // 干扰线数量
|
||||
"BubbleMinRadius": 5, // 气泡最小半径
|
||||
"BubbleMaxRadius": 10, // 气泡最大半径
|
||||
"BubbleCount": 3, // 气泡数量
|
||||
"BubbleThickness": 1.0 // 气泡边沿厚度
|
||||
}
|
||||
},
|
||||
"GrpcUrls": {
|
||||
"FindTeacher": "http://localhost:5212"
|
||||
}
|
||||
}
|
||||
|
||||
5
ZR.Admin.WebApi/loginVerifyConf.json
Normal file
5
ZR.Admin.WebApi/loginVerifyConf.json
Normal file
@ -0,0 +1,5 @@
|
||||
{
|
||||
"RSA": {
|
||||
"PrivatePem": "-----BEGIN PRIVATE KEY-----MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCjvJHH6V8fHL9zuVkW1mcDcYF5D72fEG45xLP8jyXR0/klmxZUT6My2ajGcWtOAKyca4Mcw2lKV7FRzchVyylsLi1JaH+vgbL0qwjDS0hjSm6Uqw39WFX//t1qMxX8OD5F3lvAYaNauVY6nYQ9VgEcjrq5nc+kRB7cVsR1ouQlFMQ1vLCAZwajW2pSmpjkEMYC70iJfBl7iF0za6eIVLZEpxgOi8KIkTWUDvLLH0cRR30+FgyE8wu8gh09ZbYarGyLchmAbbmERHT6jfMgKCob/ZVuh0EzrklMsFj4qdjofejzRvS/arA4HtOS1W1ZBHovPxR36quWB4DO9lvkWakNAgMBAAECggEADiLHizTQq4T12m3UDS6xchColuUO/96RRZd/2nwZTcY5Kk/7W4gMlOVJtugv1WolfNOjXCZavrpXarKTayTBDL/n1QCalXJjGtBxTzr+ouPYLCmgaZDoy9MbFoIWkdHhPnL2BOPpEHoTwbe7pPf53JdN85x2Qr5G08sB5w4LGFBRPAkOoD2LgW4QK7Ut5k4GAHmcn7nqHlkMM8ksdNGkQEhSHfoQOh7FFgR1GHJMeO0JgXprJCIFjyhtyzzDj47r02LWqEaaTdokvkYPEqyzjSI/Gufvq6nvgIlf2mU9KA2NC3VwJrXtAQQezy7yB6blvBceygwXChVKAuUtEyOf2QKBgQDaKC76PlG+p61DIwfIJIcP6JgzWVXj7gJr82hpu8NIf0Wz354eYRl1gdW6dkgpkPhnDvZ/b23P5FsWG8OR0f0VMgPvKVDo+Z+cHLsoroqeCw7B1MEdv2d69gbAk343BTVkTui94152GeCu3O/C0QmaZyqOtumEbxDl8K+lsusEkwKBgQDAI7XzXx+EqKD1m2DKnj2YILEplB4pmJnTWaZi5qAKO+XxbUTGcSxRALBYxuMEvd2AIEk9VhQiLpJ9DoOzVg5LY/zeRvK1vE2tUj/cx8X8jekdY7QayP6KigWbe3juqBHm9eD97wwmQgbFRg+ZZrpKhENym4BVqCuJwc7nC02/3wKBgFIvCyuIqKDraBE/tCHI6PysQhIuGHZKZq0mQHJ8op/AGpEdr+J/7+hdphedkaffDkU81M3DO5oyy8GzaeSYOABxHBxP80QhLejQxg0YW+4X+lI5BRtgzOn8nySTK9wsYSXNuE44xpA1RXh6kPRSbYy2SskCzUvvz2zgVDtXAMRzAoGABItTrFPdnPeYBvcLzP79GfH7/q3AIN+5E6SVKNWnh1ZvU8xvyfm3QJsxkIfzqpMLABLDaK32f/B2CnsjZkRsxh+xRViMOPwhIi5F0GTxK833a3iGM/P5ATHOfCTpcUuMUNgT4C2dLfJ10oibqdciJM0IA1fmKyB1Fyb8S76asiUCgYEAu6ZQ5BfxtbhZCjZ7/hYKHuzDjRzyiaBkKjtN5ZvqLgkG6Zdfjrm2/RcFCMVtqZKXcgVcD9yxy561fmS+5gE3yTfKiFcYoYITT/N26MJ5G7Qeb/FPpmDRVQGjCaAw0o8dvaqe3pUEROdYX+JVQMxQ4WOPiV45FXazAZtFNr8Z+xA=-----END PRIVATE KEY-----"
|
||||
}
|
||||
}
|
||||
18
ZR.Admin.WebApi/web.config
Normal file
18
ZR.Admin.WebApi/web.config
Normal file
@ -0,0 +1,18 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<configuration>
|
||||
<location path="." inheritInChildApplications="false">
|
||||
<system.webServer>
|
||||
<handlers>
|
||||
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
|
||||
</handlers>
|
||||
<aspNetCore processPath="dotnet" arguments=".\ZR.Admin.WebApi.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="inprocess" />
|
||||
</system.webServer>
|
||||
</location>
|
||||
<system.webServer>
|
||||
<security>
|
||||
<requestFiltering>
|
||||
<requestLimits maxQueryString="2097151" maxAllowedContentLength="1073741824" />
|
||||
</requestFiltering>
|
||||
</security>
|
||||
</system.webServer>
|
||||
</configuration>
|
||||
@ -171,17 +171,17 @@ $if(replaceDto.ShowBtnImport)
|
||||
/// <param name="formFile"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPost("importData")]
|
||||
[Log(Title = "${genTable.FunctionName}导入", BusinessType = BusinessType.IMPORT, IsSaveRequestData = false, IsSaveResponseData = true)]
|
||||
[Log(Title = "${genTable.FunctionName}导入", BusinessType = BusinessType.IMPORT, IsSaveRequestData = false)]
|
||||
[ActionPermissionFilter(Permission = "${replaceDto.PermissionPrefix}:import")]
|
||||
public IActionResult ImportData([FromForm(Name = "file")] IFormFile formFile)
|
||||
{
|
||||
List<${replaceDto.ModelTypeName}> list = new();
|
||||
List<${replaceDto.ModelTypeName}Dto> list = new();
|
||||
using (var stream = formFile.OpenReadStream())
|
||||
{
|
||||
list = stream.Query<${replaceDto.ModelTypeName}>(startCell: "A1").ToList();
|
||||
list = stream.Query<${replaceDto.ModelTypeName}Dto>(startCell: "A1").ToList();
|
||||
}
|
||||
|
||||
return SUCCESS(_${replaceDto.ModelTypeName}Service.Import${replaceDto.ModelTypeName}(list));
|
||||
return SUCCESS(_${replaceDto.ModelTypeName}Service.Import${replaceDto.ModelTypeName}(list.Adapt<List<${replaceDto.ModelTypeName}>>()));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -189,11 +189,11 @@ $if(replaceDto.ShowBtnImport)
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
[HttpGet("importTemplate")]
|
||||
[Log(Title = "${genTable.FunctionName}模板", BusinessType = BusinessType.EXPORT, IsSaveRequestData = true, IsSaveResponseData = false)]
|
||||
[Log(Title = "${genTable.FunctionName}模板", BusinessType = BusinessType.EXPORT, IsSaveResponseData = false)]
|
||||
[AllowAnonymous]
|
||||
public IActionResult ImportTemplateExcel()
|
||||
{
|
||||
var result = DownloadImportTemplate(new List<${replaceDto.ModelTypeName}>() { }, "${replaceDto.ModelTypeName}");
|
||||
var result = DownloadImportTemplate(new List<${replaceDto.ModelTypeName}Dto>() { }, "${replaceDto.ModelTypeName}");
|
||||
return ExportExcel(result.Item2, result.Item1);
|
||||
}
|
||||
$end
|
||||
|
||||
@ -39,6 +39,7 @@ $end
|
||||
$if(replaceDto.ShowBtnExport)
|
||||
$if(item.IsExport)
|
||||
[ExcelColumn(Name = "$if(item.ColumnComment == "")${item.CsharpField}${else}${item.ColumnComment}${end}"$if(item.CsharpType == "DateTime"), Format = "yyyy-MM-dd HH:mm:ss"$end)]
|
||||
[ExcelColumnName("$if(item.ColumnComment == "")${item.CsharpField}${else}${item.ColumnComment}${end}")]
|
||||
$else
|
||||
[ExcelIgnore]
|
||||
$end
|
||||
|
||||
@ -1,7 +1,6 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using ZR.Model.System.Generate;
|
||||
|
||||
namespace ZR.CodeGenerator
|
||||
{
|
||||
|
||||
@ -9,7 +9,7 @@ using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using ZR.CodeGenerator.Model;
|
||||
using ZR.Model.System.Generate;
|
||||
using ZR.ServiceCore.Model.Generate;
|
||||
|
||||
namespace ZR.CodeGenerator
|
||||
{
|
||||
@ -439,7 +439,7 @@ namespace ZR.CodeGenerator
|
||||
TableName = tableName,
|
||||
TableComment = desc,
|
||||
FunctionName = desc,
|
||||
Create_by = userName,
|
||||
Create_name = userName,
|
||||
Options = new Options()
|
||||
{
|
||||
SortType = "asc",
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
using System.Collections.Generic;
|
||||
using ZR.Model.System.Generate;
|
||||
using ZR.ServiceCore.Model.Generate;
|
||||
|
||||
namespace ZR.CodeGenerator.Model
|
||||
{
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net7.0</TargetFramework>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
@ -12,6 +12,6 @@
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="JinianNet.JNTemplate" Version="2.3.3" />
|
||||
<PackageReference Include="SqlSugarCoreNoDrive" Version="5.1.4.105" />
|
||||
<PackageReference Include="SqlSugarCoreNoDrive" Version="5.1.4.109" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
|
||||
@ -3,6 +3,7 @@ using Aliyun.OSS.Common;
|
||||
using Infrastructure;
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace ZR.Common
|
||||
{
|
||||
@ -55,7 +56,9 @@ namespace ZR.Common
|
||||
try
|
||||
{
|
||||
OssClient client = new(endpoint, accessKeyId, accessKeySecret);
|
||||
dirPath = dirPath.Replace("\\", "/");
|
||||
DeleteObjectResult putObjectResult = client.DeleteObject(bucketName, dirPath);
|
||||
return putObjectResult.HttpStatusCode;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@ -63,5 +66,52 @@ namespace ZR.Common
|
||||
}
|
||||
return System.Net.HttpStatusCode.BadRequest;
|
||||
}
|
||||
|
||||
public static Stream DownloadFile(string dirPath, string bucketName = "", bool isEncrypted = false)
|
||||
{
|
||||
if (string.IsNullOrEmpty(bucketName))
|
||||
{
|
||||
bucketName = bucketName1;
|
||||
}
|
||||
try
|
||||
{
|
||||
OssClient client = new(endpoint, accessKeyId, accessKeySecret);
|
||||
dirPath = dirPath.Replace("\\", "/");
|
||||
var ossObject = client.GetObject(bucketName, dirPath);
|
||||
if (isEncrypted)
|
||||
{
|
||||
try
|
||||
{
|
||||
var key = new byte[]
|
||||
{
|
||||
13, 57, 174, 2, 102, 26, 253, 192, 141, 38, 175, 244, 32, 86, 163, 25, 237, 134,
|
||||
253, 162, 62, 203, 57, 52, 56, 157, 78, 155, 63, 28, 63, 255
|
||||
};
|
||||
var iv = new byte[]
|
||||
{
|
||||
137, 221, 84, 122, 104, 162, 48, 60, 108, 130, 170, 238, 186, 190, 111, 176
|
||||
};
|
||||
var aes = Aes.Create();
|
||||
aes.Key = key;
|
||||
aes.IV = iv;
|
||||
var decryptor = aes.CreateDecryptor();
|
||||
var cryptoStream = new CryptoStream(ossObject.Content, decryptor, CryptoStreamMode.Read);
|
||||
return cryptoStream;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
// 处理异常,例如记录日志或抛出自定义异常
|
||||
Console.WriteLine($"解密文件时发生异常: {e.Message}");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
return ossObject.Content;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Console.WriteLine(e);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
269
ZR.Common/IdUtils.cs
Normal file
269
ZR.Common/IdUtils.cs
Normal file
@ -0,0 +1,269 @@
|
||||
using System;
|
||||
using SqlSugar;
|
||||
using SqlSugar.IOC;
|
||||
|
||||
namespace ZR.Common;
|
||||
|
||||
public static class IdUtils
|
||||
{
|
||||
// public static string GetSerialNumber(string code)
|
||||
// {
|
||||
// var vCode = new SugarParameter("@v_code", code);
|
||||
// var vSerialNumber = new SugarParameter("@v_serialnumber", null, true);
|
||||
// vSerialNumber.DbType = System.Data.DbType.String;
|
||||
// //TODO 会抛异常
|
||||
// DbScoped.SugarScope.GetConnectionScope(0).CopyNew().Ado.UseStoredProcedure()
|
||||
// .GetDataTable("p_get_serialnumber", vCode, vSerialNumber);
|
||||
// // .SqlQuerySingle<string>("p_get_serialnumber", vCode, vSerialNumber);
|
||||
// Console.WriteLine(vSerialNumber.Value.ToString());
|
||||
// return vSerialNumber.Value.ToString();
|
||||
// }
|
||||
|
||||
public static string GetSerialNumber(string code)
|
||||
{
|
||||
var serialNumber = string.Empty;
|
||||
|
||||
var tmpVal = string.Empty;
|
||||
var resStr = string.Empty;
|
||||
// var sp = string.Empty;
|
||||
// 当前值(加1)
|
||||
int? nextValue = 0;
|
||||
// 目标值(加cnt)
|
||||
int? destValue = 0;
|
||||
// 循环值
|
||||
int? cycleValue = 0;
|
||||
// 系统类型值
|
||||
var sysTypeValue = string.Empty;
|
||||
// 类型值
|
||||
var typeValue = string.Empty;
|
||||
|
||||
using var db = DbScoped.SugarScope.GetConnectionScope("0");
|
||||
try
|
||||
{
|
||||
db.Ado.BeginTran();
|
||||
var codeRule = db.Queryable<CodeRule>()
|
||||
.TranLock(DbLockType.Wait)
|
||||
.First(it => it.Code == code);
|
||||
if (codeRule.CurrVal == 0)
|
||||
{
|
||||
nextValue = codeRule.IniVal;
|
||||
}
|
||||
else
|
||||
{
|
||||
nextValue = codeRule.CurrVal + codeRule.Step;
|
||||
}
|
||||
|
||||
// cycleValue = codeRule.CycleVal;
|
||||
typeValue = codeRule.TypeVal;
|
||||
|
||||
cycleValue = codeRule.CycleVal ?? 1;
|
||||
|
||||
switch (codeRule.Type)
|
||||
{
|
||||
case "YYYY":
|
||||
sysTypeValue = DateTime.Now.ToString("yyyy");
|
||||
break;
|
||||
case "YYYYMM":
|
||||
sysTypeValue = DateTime.Now.ToString("yyyyMM");
|
||||
break;
|
||||
case "YYYYMMDD":
|
||||
sysTypeValue = DateTime.Now.ToString("yyyyMMdd");
|
||||
break;
|
||||
default:
|
||||
sysTypeValue = " ";
|
||||
break;
|
||||
}
|
||||
|
||||
// 循环类型值改变,初始化类型循环
|
||||
if (string.IsNullOrWhiteSpace(sysTypeValue) != string.IsNullOrWhiteSpace(typeValue))
|
||||
{
|
||||
typeValue = sysTypeValue;
|
||||
cycleValue = 1;
|
||||
nextValue = codeRule.IniVal;
|
||||
}
|
||||
|
||||
// 检查是否达到最大值,当达到最大值时抛出异常
|
||||
if (codeRule.FinishVal != null)
|
||||
{
|
||||
if (codeRule.Cycle != 1)
|
||||
{
|
||||
// 不是循环,有循环不会引发最大值错误
|
||||
if (codeRule.Step > 0)
|
||||
{
|
||||
if (nextValue > codeRule.FinishVal)
|
||||
{
|
||||
serialNumber = "-1";
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (nextValue < codeRule.FinishVal)
|
||||
{
|
||||
serialNumber = "-1";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
destValue = nextValue;
|
||||
|
||||
// 计算取值,如果非循环,数量不足时把剩下的取出返回,如果循环,则循环取
|
||||
|
||||
if (codeRule.FinishVal != null)
|
||||
{
|
||||
if (codeRule.Step > 0)
|
||||
{
|
||||
if (destValue > codeRule.FinishVal)
|
||||
{
|
||||
if (codeRule.Cycle == 1)
|
||||
{
|
||||
cycleValue = cycleValue + 1;
|
||||
destValue = codeRule.IniVal;
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (destValue < codeRule.FinishVal)
|
||||
{
|
||||
if (codeRule.Cycle == 1)
|
||||
{
|
||||
cycleValue = cycleValue + 1;
|
||||
destValue = codeRule.IniVal;
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 生成值字符串,逗号分割
|
||||
tmpVal = $"{typeValue}{destValue.ToString().PadLeft(codeRule.Width, codeRule.FillChar[0])}";
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(codeRule.Prefix))
|
||||
{
|
||||
tmpVal = $"{codeRule.Prefix}{codeRule.JoinChar ?? string.Empty}{tmpVal}";
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(codeRule.Sufix))
|
||||
{
|
||||
tmpVal = $"{tmpVal}{codeRule.JoinChar ?? string.Empty}{codeRule.Sufix}";
|
||||
}
|
||||
|
||||
resStr = tmpVal;
|
||||
|
||||
serialNumber = resStr;
|
||||
|
||||
var foundRows = db.Updateable<CodeRule>()
|
||||
.SetColumns(it => new CodeRule
|
||||
{
|
||||
TypeVal = typeValue,
|
||||
CycleVal = cycleValue,
|
||||
CurrVal = destValue,
|
||||
Version = codeRule.Version + 1
|
||||
})
|
||||
.Where(it => it.Code == code && it.Version == codeRule.Version)
|
||||
.ExecuteCommand();
|
||||
if (foundRows != 0) db.Ado.CommitTran();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
// 没有对应更新行,说明被别人更新了,重新计算
|
||||
serialNumber = "-1";
|
||||
db.Ado.RollbackTran();
|
||||
throw;
|
||||
}
|
||||
return serialNumber;
|
||||
}
|
||||
}
|
||||
[SugarTable("base_coderule")]
|
||||
[Tenant("0")]
|
||||
public class CodeRule
|
||||
{
|
||||
/// <summary>
|
||||
/// 代码
|
||||
/// </summary>
|
||||
[SugarColumn(IsPrimaryKey = true)]
|
||||
public string Code { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 名称
|
||||
/// </summary>
|
||||
public string Name { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 类型
|
||||
/// </summary>
|
||||
public string Type { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 前缀
|
||||
/// </summary>
|
||||
public string Prefix { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 宽度
|
||||
/// </summary>
|
||||
public int Width { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 初始值
|
||||
/// </summary>
|
||||
public int IniVal { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 增量
|
||||
/// </summary>
|
||||
public int Step { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 终止值
|
||||
/// </summary>
|
||||
public int? FinishVal { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 循环
|
||||
/// </summary>
|
||||
public int Cycle { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 后缀
|
||||
/// </summary>
|
||||
public string Sufix { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 分隔符
|
||||
/// </summary>
|
||||
public string JoinChar { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 填充符
|
||||
/// </summary>
|
||||
public string FillChar { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 类型值
|
||||
/// </summary>
|
||||
public string TypeVal { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 循环号
|
||||
/// </summary>
|
||||
public int? CycleVal { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 当前值
|
||||
/// </summary>
|
||||
public int? CurrVal { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 版本号
|
||||
/// </summary>
|
||||
public int Version { get; set; }
|
||||
}
|
||||
@ -6,6 +6,7 @@ using MimeKit.Text;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
|
||||
namespace ZR.Common
|
||||
{
|
||||
@ -148,5 +149,32 @@ namespace ZR.Common
|
||||
return "fail";
|
||||
}
|
||||
}
|
||||
|
||||
public string VerifyCode(int n)
|
||||
{
|
||||
var strB = new StringBuilder();
|
||||
var rand = new Random();
|
||||
for (var i = 0; i < n; i++)
|
||||
{
|
||||
var r1 = rand.Next(3);
|
||||
var r2 = 0;
|
||||
// r2为ASCII码值
|
||||
switch (r1)
|
||||
{
|
||||
case 0: // 数字: 48-57的随机数
|
||||
r2 = rand.Next(48, 58);
|
||||
break;
|
||||
case 1:
|
||||
r2 = rand.Next(65, 91); // 大写字母: 65-90的随机数
|
||||
break;
|
||||
case 2:
|
||||
r2 = rand.Next(97, 123); // 小写字母: 97-122的随机数
|
||||
break;
|
||||
}
|
||||
|
||||
strB.Append((char)r2);
|
||||
}
|
||||
return strB.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,5 +1,7 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
@ -126,5 +128,31 @@ namespace ZR.Common
|
||||
|
||||
return true; //由数字、字母、符号构成的密码
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取文件的MD5值
|
||||
/// </summary>
|
||||
/// <param name="filestream">文件流</param>
|
||||
/// <returns></returns>
|
||||
public static string GetMD5HashFromFile(Stream filestream)
|
||||
{
|
||||
try
|
||||
{
|
||||
MD5 md5 = new MD5CryptoServiceProvider();
|
||||
byte[] retVal = md5.ComputeHash(filestream);
|
||||
filestream.Close();
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (int i = 0; i < retVal.Length; i++)
|
||||
{
|
||||
sb.Append(retVal[i].ToString("x2"));
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Console.WriteLine(e);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net7.0</TargetFramework>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
37
ZR.Model/BaseModel.cs
Normal file
37
ZR.Model/BaseModel.cs
Normal file
@ -0,0 +1,37 @@
|
||||
using MiniExcelLibs.Attributes;
|
||||
|
||||
namespace ZR.Model;
|
||||
|
||||
public class BaseModel
|
||||
{
|
||||
[SugarColumn(IsOnlyIgnoreUpdate = true)]
|
||||
[JsonProperty(propertyName: "CreateBy")]
|
||||
[ExcelIgnore]
|
||||
public long CreateBy { get; set; }
|
||||
|
||||
[SugarColumn(IsOnlyIgnoreUpdate = true)]
|
||||
[JsonProperty(propertyName: "CreateName")]
|
||||
[ExcelIgnore]
|
||||
public string CreateName { get; set; }
|
||||
|
||||
[SugarColumn(IsOnlyIgnoreUpdate = true)]
|
||||
[JsonProperty(propertyName: "CreateTime")]
|
||||
[ExcelColumn(Format = "yyyy-MM-dd HH:mm:ss")]
|
||||
public DateTime CreateTime { get; set; } = DateTime.Now;
|
||||
|
||||
[SugarColumn(IsOnlyIgnoreInsert = true)]
|
||||
[JsonProperty(propertyName: "UpdateBy")]
|
||||
[ExcelIgnore]
|
||||
public long UpdateBy { get; set; }
|
||||
|
||||
[SugarColumn(IsOnlyIgnoreInsert = true)]
|
||||
[JsonProperty(propertyName: "UpdateName")]
|
||||
[ExcelIgnore]
|
||||
public string UpdateName { get; set; }
|
||||
|
||||
[SugarColumn(IsOnlyIgnoreInsert = true, IsNullable = true)]
|
||||
[JsonProperty(propertyName: "UpdateTime")]
|
||||
[ExcelIgnore]
|
||||
public DateTime? UpdateTime { get; set; }
|
||||
|
||||
}
|
||||
23
ZR.Model/MyDiary.cs
Normal file
23
ZR.Model/MyDiary.cs
Normal file
@ -0,0 +1,23 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ZR.Model
|
||||
{
|
||||
[SugarTable("my_diary")]
|
||||
public class MyDiary
|
||||
{
|
||||
[SugarColumn(IsPrimaryKey = true)]
|
||||
[JsonConverter(typeof(ValueToStringConverter))]
|
||||
public long Id { get; set; }
|
||||
|
||||
public string Content { get; set; }
|
||||
|
||||
[JsonConverter(typeof(ValueToStringConverter))]
|
||||
public long UserId { get; set; }
|
||||
|
||||
public DateTime CreateTime { get; set; }
|
||||
}
|
||||
}
|
||||
@ -1,7 +1,7 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net7.0</TargetFramework>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<GenerateDocumentationFile>true</GenerateDocumentationFile>
|
||||
<NoWarn>1701;1702;1591;1570</NoWarn>
|
||||
</PropertyGroup>
|
||||
@ -9,7 +9,11 @@
|
||||
<ItemGroup>
|
||||
<PackageReference Include="MiniExcel" Version="1.31.2" />
|
||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
|
||||
<PackageReference Include="SqlSugarCoreNoDrive" Version="5.1.4.105" />
|
||||
<PackageReference Include="SqlSugarCoreNoDrive" Version="5.1.4.109" />
|
||||
<PackageReference Include="System.ComponentModel.Annotations" Version="5.0.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Infrastructure\ZR.Infrastructure.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
|
||||
@ -58,14 +58,38 @@ namespace ZR.Repository
|
||||
{
|
||||
return Context.Insertable(t);
|
||||
}
|
||||
public IInsertable<T> Insertable(List<T> t)
|
||||
{
|
||||
return Context.Insertable<T>(t);
|
||||
}
|
||||
public IInsertable<T> Insertable(T[] t)
|
||||
{
|
||||
return Context.Insertable<T>(t);
|
||||
}
|
||||
public InsertNavTaskInit<T, T> InsertNav(T t)
|
||||
{
|
||||
return Context.InsertNav(t);
|
||||
}
|
||||
public InsertNavTaskInit<T, T> InsertNav(List<T> t)
|
||||
{
|
||||
return Context.InsertNav(t);
|
||||
}
|
||||
#endregion add
|
||||
|
||||
#region update
|
||||
//public IUpdateable<T> Updateable(T entity)
|
||||
//{
|
||||
// return Context.Updateable(entity);
|
||||
//}
|
||||
|
||||
public IUpdateable<T> Updateable(T entity)
|
||||
{
|
||||
return Context.Updateable(entity);
|
||||
}
|
||||
public IUpdateable<T> Updateable(List<T> t)
|
||||
{
|
||||
return Context.Updateable<T>(t);
|
||||
}
|
||||
public IUpdateable<T> Updateable(T[] t)
|
||||
{
|
||||
return Context.Updateable<T>(t);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 实体根据主键更新
|
||||
/// </summary>
|
||||
@ -114,7 +138,25 @@ namespace ZR.Repository
|
||||
{
|
||||
return Context.Updateable<T>().SetColumns(columns).Where(where).RemoveDataCache().ExecuteCommand();
|
||||
}
|
||||
|
||||
public UpdateNavTaskInit<T, T> UpdateNav(T t)
|
||||
{
|
||||
return Context.UpdateNav(t);
|
||||
}
|
||||
|
||||
public UpdateNavTaskInit<T, T> UpdateNav(List<T> t)
|
||||
{
|
||||
return Context.UpdateNav(t);
|
||||
}
|
||||
#endregion update
|
||||
public IStorageable<T> Storageable(T t)
|
||||
{
|
||||
return Context.Storageable<T>(t);
|
||||
}
|
||||
public IStorageable<T> Storageable(List<T> t)
|
||||
{
|
||||
return Context.Storageable(t);
|
||||
}
|
||||
|
||||
public DbResult<bool> UseTran(Action action)
|
||||
{
|
||||
@ -190,6 +232,10 @@ namespace ZR.Repository
|
||||
{
|
||||
return Context.DbMaintenance.TruncateTable<T>();
|
||||
}
|
||||
public DeleteNavTaskInit<T, T> DeleteNav(Expression<Func<T, bool>> whereExpression)
|
||||
{
|
||||
return Context.DeleteNav(whereExpression);
|
||||
}
|
||||
#endregion delete
|
||||
|
||||
#region query
|
||||
|
||||
@ -16,9 +16,17 @@ namespace ZR.Repository
|
||||
int Insert(T parm, Expression<Func<T, object>> iClumns = null, bool ignoreNull = true);
|
||||
|
||||
IInsertable<T> Insertable(T t);
|
||||
IInsertable<T> Insertable(List<T> t);
|
||||
IInsertable<T> Insertable(T[] t);
|
||||
InsertNavTaskInit<T, T> InsertNav(T t);
|
||||
InsertNavTaskInit<T, T> InsertNav(List<T> t);
|
||||
#endregion add
|
||||
|
||||
#region update
|
||||
IUpdateable<T> Updateable(T entity);
|
||||
IUpdateable<T> Updateable(List<T> t);
|
||||
IUpdateable<T> Updateable(T[] t);
|
||||
|
||||
int Update(T entity, bool ignoreNullColumns = false, object data = null);
|
||||
|
||||
/// <summary>
|
||||
@ -32,8 +40,14 @@ namespace ZR.Repository
|
||||
int Update(T entity, Expression<Func<T, object>> expression, Expression<Func<T, bool>> where);
|
||||
|
||||
int Update(Expression<Func<T, bool>> where, Expression<Func<T, T>> columns);
|
||||
|
||||
UpdateNavTaskInit<T, T> UpdateNav(T t);
|
||||
|
||||
UpdateNavTaskInit<T, T> UpdateNav(List<T> t);
|
||||
#endregion update
|
||||
IStorageable<T> Storageable(T t);
|
||||
IStorageable<T> Storageable(List<T> t);
|
||||
|
||||
DbResult<bool> UseTran(Action action);
|
||||
|
||||
DbResult<bool> UseTran(SqlSugarClient client, Action action);
|
||||
@ -46,7 +60,7 @@ namespace ZR.Repository
|
||||
int Delete(object id, string title = "");
|
||||
int DeleteTable();
|
||||
bool Truncate();
|
||||
|
||||
DeleteNavTaskInit<T, T> DeleteNav(Expression<Func<T, bool>> whereExpression);
|
||||
#endregion delete
|
||||
|
||||
#region query
|
||||
|
||||
@ -1,18 +1,15 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net7.0</TargetFramework>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Infrastructure\ZR.Infrastructure.csproj" />
|
||||
<ProjectReference Include="..\ZR.Model\ZR.Model.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Mapster" Version="7.3.0" />
|
||||
<PackageReference Include="MySqlConnector" Version="2.2.6" />
|
||||
<PackageReference Include="SqlSugar.IOC" Version="2.0.0" />
|
||||
<PackageReference Include="SqlSugarCoreNoDrive" Version="5.1.4.105" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
|
||||
@ -1,4 +1,5 @@
|
||||
global using System.Collections.Generic;
|
||||
global using System;
|
||||
global using SqlSugar;
|
||||
global using Newtonsoft.Json;
|
||||
global using Newtonsoft.Json;
|
||||
global using Infrastructure.Attribute;
|
||||
@ -5,6 +5,7 @@ using ZR.Model.System;
|
||||
using ZR.Repository;
|
||||
using ZR.Service.IService;
|
||||
using ZR.Service.System.IService;
|
||||
using ZR.ServiceCore.Model;
|
||||
|
||||
namespace ZR.Service
|
||||
{
|
||||
|
||||
@ -1,4 +1,5 @@
|
||||
using ZR.Model.System;
|
||||
using ZR.ServiceCore.Model;
|
||||
|
||||
namespace ZR.Service.IService
|
||||
{
|
||||
|
||||
14
ZR.Service/IService/IMyDiaryService.cs
Normal file
14
ZR.Service/IService/IMyDiaryService.cs
Normal file
@ -0,0 +1,14 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using ZR.Model;
|
||||
|
||||
namespace ZR.Service.IService
|
||||
{
|
||||
public interface IMyDiaryService : IBaseService<MyDiary>
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
15
ZR.Service/MyDiaryService.cs
Normal file
15
ZR.Service/MyDiaryService.cs
Normal file
@ -0,0 +1,15 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using ZR.Model;
|
||||
using ZR.Service.IService;
|
||||
|
||||
namespace ZR.Service
|
||||
{
|
||||
[AppService(ServiceType = typeof(IMyDiaryService), ServiceLifetime = LifeTime.Transient)]
|
||||
public class MyDiaryService : BaseService<MyDiary>, IMyDiaryService
|
||||
{
|
||||
}
|
||||
}
|
||||
@ -1,7 +1,7 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net7.0</TargetFramework>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<GenerateDocumentationFile>true</GenerateDocumentationFile>
|
||||
</PropertyGroup>
|
||||
|
||||
@ -5,6 +5,7 @@ using Microsoft.AspNetCore.Mvc.Filters;
|
||||
using ZR.Model.System;
|
||||
using ZR.Service.System;
|
||||
using ZR.Service.System.IService;
|
||||
using ZR.ServiceCore.Model;
|
||||
|
||||
namespace ZR.ServiceCore.Middleware
|
||||
{
|
||||
|
||||
132
ZR.ServiceCore/Filters/DataFieldFilter.cs
Normal file
132
ZR.ServiceCore/Filters/DataFieldFilter.cs
Normal file
@ -0,0 +1,132 @@
|
||||
using System.Collections;
|
||||
using Infrastructure;
|
||||
using Infrastructure.Model;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.Filters;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Newtonsoft.Json.Serialization;
|
||||
using NLog;
|
||||
using SqlSugar.IOC;
|
||||
using ZR.Infrastructure.Resolver;
|
||||
using ZR.ServiceCore.Model;
|
||||
|
||||
namespace ZR.ServiceCore.Filters;
|
||||
public class DataFieldFilter : ActionFilterAttribute
|
||||
{
|
||||
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
|
||||
|
||||
public DataFieldFilter(Type resultType)
|
||||
{
|
||||
ResultType = resultType;
|
||||
}
|
||||
|
||||
public DataFieldFilter()
|
||||
{
|
||||
}
|
||||
|
||||
public Type ResultType { get; set; }
|
||||
|
||||
public string Path { get; set; }
|
||||
|
||||
public override void OnResultExecuting(ResultExecutingContext context)
|
||||
{
|
||||
// var url = httpContext.Request.Path;
|
||||
var info = JwtUtil.GetLoginUser(context.HttpContext);
|
||||
var roleIds = info.Roles.Select(it => it.RoleId).ToList();
|
||||
// var list = DbScoped.SugarScope.Queryable<PoRequirement>().ToList();
|
||||
var list = DbScoped.SugarScope.Queryable<SysField>()
|
||||
.LeftJoin<SysRoleField>((sf, srf) => sf.Id == srf.FieldId)
|
||||
.Where((sf, srf) => roleIds.Contains(srf.RoleId))
|
||||
.ToList();
|
||||
|
||||
// 获取原始的结果
|
||||
var originalResult = context.Result as ContentResult;
|
||||
var apiResult = (JsonConvert.DeserializeObject<ApiResult>(originalResult?.Content!)) as ApiResult;
|
||||
// 创建泛型类型
|
||||
var resObj = typeof(JObject).GetMethod("ToObject", Type.EmptyTypes)?
|
||||
.MakeGenericMethod(ResultType).Invoke(apiResult?["data"], null)!;
|
||||
SetPropertiesToNull(resObj, list.Select(it => it.FieldName).ToList());
|
||||
// var json = JsonConvert.SerializeObject(resObj, new JsonSerializerSettings
|
||||
// {
|
||||
// ContractResolver = new CamelCasePropertyNamesContractResolver()
|
||||
// });
|
||||
// var jObject = JObject.Parse(json);
|
||||
apiResult["data"] = resObj;
|
||||
var jsonRes = JsonConvert.SerializeObject(apiResult, new JsonSerializerSettings
|
||||
{
|
||||
ContractResolver = new CamelCasePropertyNamesContractResolver()
|
||||
});
|
||||
// JsonConvert.SerializeObject(apiResult, new JsonSerializerSettings
|
||||
// {
|
||||
// ContractResolver = new JsonPropertyContractResolver(
|
||||
// list.Select(it => ToLowerFirstLetter(it.FieldName)).ToList()
|
||||
// )
|
||||
// })
|
||||
context.Result = new ContentResult{ Content = jsonRes,
|
||||
ContentType = "application/json"} ;
|
||||
base.OnResultExecuting(context);
|
||||
}
|
||||
|
||||
private static void SetPropertiesToNull(object obj, IEnumerable<string> props)
|
||||
{
|
||||
var type = obj.GetType();
|
||||
var properties = type.GetProperties();
|
||||
foreach (var property in properties)
|
||||
{
|
||||
if (obj.IsEmpty())
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (props.Contains(property.Name))
|
||||
{
|
||||
property.SetValue(obj, null);
|
||||
}
|
||||
else if (property.PropertyType.IsArray)
|
||||
{
|
||||
var arrayValue = (Array)property.GetValue(obj);
|
||||
if (arrayValue != null)
|
||||
{
|
||||
foreach (var element in arrayValue)
|
||||
{
|
||||
SetPropertiesToNull(element, props);
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (property.PropertyType.IsGenericType &&
|
||||
property.PropertyType.GetGenericTypeDefinition() == typeof(List<>))
|
||||
{
|
||||
// 属性的类型是 List<T>
|
||||
var listValue = (IEnumerable)property.GetValue(obj);
|
||||
if (listValue != null)
|
||||
{
|
||||
foreach (var element in listValue)
|
||||
{
|
||||
SetPropertiesToNull(element, props);
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (property.PropertyType.GetInterface("IDictionary") != null ||
|
||||
property.PropertyType.GetInterface("IDictionary`2") != null)
|
||||
{
|
||||
|
||||
}
|
||||
else if (property.PropertyType.IsClass && property.PropertyType != typeof(string))
|
||||
{
|
||||
var name = property.Name;
|
||||
var prop = property.GetValue(obj);
|
||||
SetPropertiesToNull(prop, props);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static string ToLowerFirstLetter(string str)
|
||||
{
|
||||
if (!str.IsNotEmpty())
|
||||
{
|
||||
return str;
|
||||
}
|
||||
var charArray = str.ToCharArray();
|
||||
charArray[0] = char.ToLower(charArray[0]);
|
||||
return new string(charArray);
|
||||
}
|
||||
}
|
||||
@ -9,6 +9,7 @@ using Microsoft.AspNetCore.Mvc.Filters;
|
||||
using NLog;
|
||||
using ZR.Model.System;
|
||||
using ZR.Service.System.IService;
|
||||
using ZR.ServiceCore.Model;
|
||||
|
||||
namespace ZR.ServiceCore.Middleware
|
||||
{
|
||||
|
||||
47
ZR.ServiceCore/Middleware/CustomIpRateLimitMiddleware.cs
Normal file
47
ZR.ServiceCore/Middleware/CustomIpRateLimitMiddleware.cs
Normal file
@ -0,0 +1,47 @@
|
||||
using AspNetCoreRateLimit;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using NLog;
|
||||
using ZR.ServiceCore.Model;
|
||||
using ZR.ServiceCore.Services.IService;
|
||||
using RateLimitRule = AspNetCoreRateLimit.RateLimitRule;
|
||||
|
||||
namespace ZR.ServiceCore.Middleware;
|
||||
|
||||
public class CustomIpRateLimitMiddleware : IpRateLimitMiddleware
|
||||
{
|
||||
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
|
||||
|
||||
private readonly IIpRateLimitLogService _ipRateLimitLogService;
|
||||
|
||||
public CustomIpRateLimitMiddleware(RequestDelegate next, IProcessingStrategy processingStrategy,
|
||||
IOptions<IpRateLimitOptions> options, IIpPolicyStore policyStore, IRateLimitConfiguration config,
|
||||
ILogger<IpRateLimitMiddleware> logger, IIpRateLimitLogService ipRateLimitLogService) : base(next, processingStrategy, options, policyStore, config, logger)
|
||||
{
|
||||
_ipRateLimitLogService = ipRateLimitLogService;
|
||||
}
|
||||
|
||||
protected override void LogBlockedRequest(HttpContext httpContext, ClientRequestIdentity identity,
|
||||
RateLimitCounter counter, RateLimitRule rule)
|
||||
{
|
||||
// base.LogBlockedRequest(httpContext, identity, counter, rule);
|
||||
var nowDate = DateTime.Now;
|
||||
var ipRateLimitLog = new IpRateLimitLog
|
||||
{
|
||||
HttpVerb = identity.HttpVerb,
|
||||
Path = identity.Path,
|
||||
ClientIp = identity.ClientIp,
|
||||
Limit = rule.Limit,
|
||||
Period = rule.Period,
|
||||
Exceeded = counter.Count - rule.Limit,
|
||||
Endpoint = rule.Endpoint,
|
||||
CreateTime = nowDate
|
||||
};
|
||||
var logStr = $"请求 {ipRateLimitLog.HttpVerb}:{ipRateLimitLog.Path} 来自 IP {ipRateLimitLog.ClientIp} 已被阻止, " +
|
||||
$"配额 {ipRateLimitLog.Limit}/{ipRateLimitLog.Period} 超出次数 {ipRateLimitLog.Exceeded}. " +
|
||||
$"被规则 {ipRateLimitLog.Endpoint} 阻止. 时间: {ipRateLimitLog.CreateTime}";
|
||||
Logger.Info(logStr);
|
||||
_ipRateLimitLogService.InsertIpRateLimitLogAsync(ipRateLimitLog);
|
||||
}
|
||||
}
|
||||
@ -6,9 +6,11 @@ using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.Features;
|
||||
using NLog;
|
||||
using System.Text.Encodings.Web;
|
||||
using Microsoft.AspNetCore.Routing;
|
||||
using ZR.Common;
|
||||
using ZR.Model.System;
|
||||
using ZR.Service.System.IService;
|
||||
using ZR.ServiceCore.Model;
|
||||
using textJson = System.Text.Json;
|
||||
|
||||
namespace ZR.ServiceCore.Middleware
|
||||
@ -49,6 +51,9 @@ namespace ZR.ServiceCore.Middleware
|
||||
string msg;
|
||||
string error = string.Empty;
|
||||
bool notice = true;
|
||||
var stackTrace = string.Empty;
|
||||
var controller = context.GetRouteData().Values["Controller"].ToString();
|
||||
var action = context.GetRouteData().Values["Action"].ToString();
|
||||
//自定义异常
|
||||
if (ex is CustomException customException)
|
||||
{
|
||||
@ -56,6 +61,7 @@ namespace ZR.ServiceCore.Middleware
|
||||
msg = customException.Message;
|
||||
error = customException.LogMsg;
|
||||
notice = customException.Notice;
|
||||
stackTrace = customException.StackTrace;
|
||||
}
|
||||
else if (ex is ArgumentException)//参数异常
|
||||
{
|
||||
@ -68,6 +74,7 @@ namespace ZR.ServiceCore.Middleware
|
||||
error = $"{ex.Message}";
|
||||
logLevel = LogLevel.Error;
|
||||
context.Response.StatusCode = 500;
|
||||
stackTrace = ex.StackTrace;
|
||||
}
|
||||
var options = new textJson.JsonSerializerOptions
|
||||
{
|
||||
@ -89,8 +96,10 @@ namespace ZR.ServiceCore.Middleware
|
||||
RequestMethod = context.Request.Method,
|
||||
JsonResult = responseResult,
|
||||
ErrorMsg = string.IsNullOrEmpty(error) ? msg : error,
|
||||
StackTrace = stackTrace,
|
||||
OperName = HttpContextExtension.GetName(context),
|
||||
OperLocation = ip_info.Province + " " + ip_info.City,
|
||||
Method = controller + "." + action + "()",
|
||||
OperTime = DateTime.Now,
|
||||
OperParam = HttpContextExtension.GetRequestValue(context, context.Request.Method)
|
||||
};
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
namespace ZR.Model.System
|
||||
using ZR.Model.System;
|
||||
|
||||
namespace ZR.ServiceCore.Model
|
||||
{
|
||||
/// <summary>
|
||||
/// 文章表
|
||||
@ -77,5 +79,7 @@
|
||||
|
||||
[Navigate(NavigateType.OneToOne, nameof(CategoryId), nameof(ArticleCategory.CategoryId))] //自定义关系映射
|
||||
public ArticleCategory ArticleCategoryNav { get; set; }
|
||||
[SugarColumn(IsIgnore = true)]
|
||||
public string IsPaa { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,9 +1,4 @@
|
||||
using Newtonsoft.Json;
|
||||
using SqlSugar;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace ZR.Model.System
|
||||
namespace ZR.ServiceCore.Model
|
||||
{
|
||||
/// <summary>
|
||||
/// 文章目录
|
||||
|
||||
89
ZR.ServiceCore/Model/BaseCodeRule.cs
Normal file
89
ZR.ServiceCore/Model/BaseCodeRule.cs
Normal file
@ -0,0 +1,89 @@
|
||||
namespace ZR.Model.System;
|
||||
/// <summary>
|
||||
/// 编码规则表
|
||||
/// </summary>
|
||||
[SugarTable("base_coderule")]
|
||||
[Tenant("0")]
|
||||
public class BaseCodeRule
|
||||
{
|
||||
/// <summary>
|
||||
/// 代码
|
||||
/// </summary>
|
||||
[SugarColumn(IsPrimaryKey = true)]
|
||||
public string Code { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 名称
|
||||
/// </summary>
|
||||
public string Name { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 类型
|
||||
/// </summary>
|
||||
public string Type { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 前缀
|
||||
/// </summary>
|
||||
public string Prefix { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 宽度
|
||||
/// </summary>
|
||||
public int Width { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 初始值
|
||||
/// </summary>
|
||||
public int IniVal { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 增量
|
||||
/// </summary>
|
||||
public int Step { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 终止值
|
||||
/// </summary>
|
||||
public int FinishVal { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 循环
|
||||
/// </summary>
|
||||
public int Cycle { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 后缀
|
||||
/// </summary>
|
||||
public string Sufix { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 分隔符
|
||||
/// </summary>
|
||||
public string JoinChar { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 填充符
|
||||
/// </summary>
|
||||
public string FillChar { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 类型值
|
||||
/// </summary>
|
||||
public string TypeVal { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 循环号
|
||||
/// </summary>
|
||||
public int CycleVal { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 当前值
|
||||
/// </summary>
|
||||
public int CurrVal { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 版本号
|
||||
/// </summary>
|
||||
public int Version { get; set; }
|
||||
}
|
||||
@ -1,9 +1,6 @@
|
||||
using Newtonsoft.Json;
|
||||
using SqlSugar;
|
||||
using System;
|
||||
using System.ComponentModel;
|
||||
|
||||
namespace ZR.Model.Models
|
||||
namespace ZR.ServiceCore.Model
|
||||
{
|
||||
/// <summary>
|
||||
/// 多语言配置,数据实体对象
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
using System;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using ZR.Model;
|
||||
|
||||
namespace ZR.Model.Dto
|
||||
namespace ZR.ServiceCore.Model.Dto
|
||||
{
|
||||
/// <summary>
|
||||
/// 文章目录输入对象
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user