解决文件本地上传报错问题,速率限制独立配置文件,解决通知公告修改删除报错,nlog增加速率限制日志文件写入,增加业务单号模块,生成业务单号工具类,IIS部署用web.config

This commit is contained in:
YUN-PC5\user 2023-10-19 16:28:09 +08:00
parent 5174fc9ec0
commit 99d2ebcbe8
20 changed files with 598 additions and 73 deletions

View File

@ -17,6 +17,8 @@
<PackageReference Include="Microsoft.Extensions.DependencyModel" Version="7.0.0" /> <PackageReference Include="Microsoft.Extensions.DependencyModel" Version="7.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" /> <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="RulesEngine" Version="5.0.2" /> <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="UAParser" Version="3.1.47" />
<PackageReference Include="IPTools.China" Version="1.6.0" /> <PackageReference Include="IPTools.China" Version="1.6.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="7.0.7" /> <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="7.0.7" />

View File

@ -1,5 +1,7 @@
using System.Net; using System.Net;
using System.Net.Sockets; using System.Net.Sockets;
using Infrastructure.Helper;
using JinianNet.JNTemplate;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using Newtonsoft.Json; using Newtonsoft.Json;
@ -9,6 +11,7 @@ using ZR.Service.IService;
using ZR.Service.System; using ZR.Service.System;
using ZR.Service.System.IService; using ZR.Service.System.IService;
using ZR.ServiceCore.Model; using ZR.ServiceCore.Model;
using ZR.ServiceCore.Services.IService;
namespace ZR.Admin.WebApi.Controllers namespace ZR.Admin.WebApi.Controllers
{ {
@ -47,8 +50,11 @@ namespace ZR.Admin.WebApi.Controllers
[HttpGet] [HttpGet]
public IActionResult Index() public IActionResult Index()
{ {
return Ok("看到这里页面说明你已经成功启动了本项目:)\n\n" + var contentTpl = JnHelper.ReadTemplate("", "logo.txt");
"如果觉得项目有用,打赏作者喝杯咖啡作为奖励\n☛☛http://www.izhaorui.cn/doc/support.html\n"); 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> /// <summary>
@ -160,7 +166,7 @@ namespace ZR.Admin.WebApi.Controllers
uploadDto.FileDir = OptionsSetting.Upload.LocalSavePath; uploadDto.FileDir = OptionsSetting.Upload.LocalSavePath;
} }
file = await SysFileService.SaveFileToLocal(savePath, uploadDto.FileName, uploadDto.FileDir, file = await SysFileService.SaveFileToLocal(savePath, uploadDto.FileName, uploadDto.FileDir,
HttpContext.GetName(), formFile, scheme + serverIP); HttpContext.GetUId(), HttpContext.GetName(), formFile, scheme + serverIP);
break; break;
case StoreType.REMOTE: case StoreType.REMOTE:
break; break;
@ -174,7 +180,8 @@ namespace ZR.Admin.WebApi.Controllers
{ {
return ToResponse(ResultCode.CUSTOM_ERROR, "上传文件过大,不能超过 " + AlimaxContentLength + " MB"); 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.GetName())
{ {
StoreType = (int)StoreType.ALIYUN, StoreType = (int)StoreType.ALIYUN,
FileType = formFile.ContentType FileType = formFile.ContentType

View 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);
}
}

View File

@ -5,6 +5,7 @@ using ZR.Model.System;
using ZR.Service.System.IService; using ZR.Service.System.IService;
using ZR.ServiceCore.Model; using ZR.ServiceCore.Model;
using ZR.ServiceCore.Model.Dto; using ZR.ServiceCore.Model.Dto;
using ZR.ServiceCore.Services.IService;
namespace ZR.Admin.WebApi.Controllers namespace ZR.Admin.WebApi.Controllers
{ {

View File

@ -22,12 +22,12 @@ namespace ZR.Admin.WebApi.Controllers.System
/// <summary> /// <summary>
/// 通知公告表接口 /// 通知公告表接口
/// </summary> /// </summary>
private readonly ISysNoticeService _SysNoticeService; private readonly ISysNoticeService _sysNoticeService;
private readonly IHubContext<MessageHub> _hubContext; private readonly IHubContext<MessageHub> _hubContext;
public SysNoticeController(ISysNoticeService SysNoticeService, IHubContext<MessageHub> hubContext) public SysNoticeController(ISysNoticeService sysNoticeService, IHubContext<MessageHub> hubContext)
{ {
_SysNoticeService = SysNoticeService; _sysNoticeService = sysNoticeService;
_hubContext = hubContext; _hubContext = hubContext;
} }
@ -41,7 +41,7 @@ namespace ZR.Admin.WebApi.Controllers.System
var predicate = Expressionable.Create<SysNotice>(); var predicate = Expressionable.Create<SysNotice>();
predicate = predicate.And(m => m.Status == 0); predicate = predicate.And(m => m.Status == 0);
var response = _SysNoticeService.GetPages(predicate.ToExpression(), parm); var response = _sysNoticeService.GetPages(predicate.ToExpression(), parm);
return SUCCESS(response); return SUCCESS(response);
} }
@ -53,19 +53,19 @@ namespace ZR.Admin.WebApi.Controllers.System
[ActionPermissionFilter(Permission = "system:notice:list")] [ActionPermissionFilter(Permission = "system:notice:list")]
public IActionResult QuerySysNotice([FromQuery] SysNoticeQueryDto parm) public IActionResult QuerySysNotice([FromQuery] SysNoticeQueryDto parm)
{ {
PagedInfo<SysNotice> response = _SysNoticeService.GetPageList(parm); PagedInfo<SysNotice> response = _sysNoticeService.GetPageList(parm);
return SUCCESS(response); return SUCCESS(response);
} }
/// <summary> /// <summary>
/// 查询通知公告表详情 /// 查询通知公告表详情
/// </summary> /// </summary>
/// <param name="NoticeId"></param> /// <param name="noticeId"></param>
/// <returns></returns> /// <returns></returns>
[HttpGet("{NoticeId}")] [HttpGet("{noticeId}")]
public IActionResult GetSysNotice(int 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); return SUCCESS(response);
} }
@ -95,7 +95,7 @@ namespace ZR.Admin.WebApi.Controllers.System
// it.Create_time // it.Create_time
// }); // });
var result = _SysNoticeService.Insertable(modal).ExecuteReturnSnowflakeId(); var result = _sysNoticeService.Insertable(modal).ExecuteReturnSnowflakeId();
return SUCCESS(result); return SUCCESS(result);
} }
@ -114,7 +114,7 @@ namespace ZR.Admin.WebApi.Controllers.System
.Map(dest => dest.NoticeId, src => src.NoticeId.ParseToLong()); .Map(dest => dest.NoticeId, src => src.NoticeId.ParseToLong());
var model = parm.Adapt<SysNotice>(config).ToUpdate(HttpContext); var model = parm.Adapt<SysNotice>(config).ToUpdate(HttpContext);
var response = _SysNoticeService.Update(w => w.NoticeId == model.NoticeId, it => new SysNotice() var response = _sysNoticeService.Update(w => w.NoticeId == model.NoticeId, it => new SysNotice()
{ {
NoticeTitle = model.NoticeTitle, NoticeTitle = model.NoticeTitle,
NoticeType = model.NoticeType, NoticeType = model.NoticeType,
@ -132,16 +132,16 @@ namespace ZR.Admin.WebApi.Controllers.System
/// 发送通知公告表 /// 发送通知公告表
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
[HttpPut("send/{NoticeId}")] [HttpPut("send/{noticeId}")]
[ActionPermissionFilter(Permission = "system:notice:update")] [ActionPermissionFilter(Permission = "system:notice:update")]
[Log(Title = "发送通知公告", BusinessType = BusinessType.OTHER)] [Log(Title = "发送通知公告", BusinessType = BusinessType.OTHER)]
public IActionResult SendNotice(long NoticeId = 0) public IActionResult SendNotice(long noticeId = 0)
{ {
if (NoticeId <= 0) if (noticeId <= 0)
{ {
throw new CustomException("请求实体不能为空"); 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) if (response != null && response.Status == 0)
{ {
_hubContext.Clients.All.SendAsync(HubsConstant.ReceiveNotice, response.NoticeTitle, response.NoticeContent); _hubContext.Clients.All.SendAsync(HubsConstant.ReceiveNotice, response.NoticeTitle, response.NoticeContent);
@ -158,10 +158,10 @@ namespace ZR.Admin.WebApi.Controllers.System
[Log(Title = "通知公告", BusinessType = BusinessType.DELETE)] [Log(Title = "通知公告", BusinessType = BusinessType.DELETE)]
public IActionResult DeleteSysNotice(string ids) public IActionResult DeleteSysNotice(string ids)
{ {
int[] idsArr = Tools.SpitIntArrary(ids); var idsArr = Tools.SpitLongArrary(ids);
if (idsArr.Length <= 0) { return ToResponse(ApiResult.Error($"删除失败Id 不能为空")); } if (idsArr.Length <= 0) { return ToResponse(ApiResult.Error($"删除失败Id 不能为空")); }
var response = _SysNoticeService.Delete(idsArr); var response = _sysNoticeService.Delete(idsArr);
return SUCCESS(response); return SUCCESS(response);
} }

View File

@ -6,6 +6,7 @@ using ZR.Model.System;
using ZR.Service.System.IService; using ZR.Service.System.IService;
using ZR.ServiceCore.Model; using ZR.ServiceCore.Model;
using ZR.ServiceCore.Model.Dto; using ZR.ServiceCore.Model.Dto;
using ZR.ServiceCore.Services.IService;
namespace ZR.Admin.WebApi.Controllers.System namespace ZR.Admin.WebApi.Controllers.System
{ {
@ -133,7 +134,7 @@ namespace ZR.Admin.WebApi.Controllers.System
} }
var file = await FileService.SaveFileToLocal(hostEnvironment.WebRootPath, "", "avatar", var file = await FileService.SaveFileToLocal(hostEnvironment.WebRootPath, "", "avatar",
HttpContext.GetName(), formFile, serverIP); HttpContext.GetUId(), HttpContext.GetName(), formFile, serverIP);
UserService.UpdatePhoto(new SysUser() { Avatar = file.AccessUrl, UserId = userId }); UserService.UpdatePhoto(new SysUser() { Avatar = file.AccessUrl, UserId = userId });
return SUCCESS(new { imgUrl = file.AccessUrl }); return SUCCESS(new { imgUrl = file.AccessUrl });

View 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": [
]
}
}

View File

@ -71,7 +71,18 @@
<!--写入黑洞--> <!--写入黑洞-->
<target name="blackhole" xsi:type="Null" /> <target name="blackhole" xsi:type="Null" />
<target name="ipRateLimit" xsi:type="ColoredConsole" useDefaultRowHighlightingRules="false" <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}"> layout="${date:format=MM-dd HH\:mm\:ss} | ${aspnet-request-url} ${newline} ${message}">
<highlight-row condition="level == LogLevel.Info" foregroundColor="Blue" /> <highlight-row condition="level == LogLevel.Info" foregroundColor="Blue" />
</target> </target>
@ -88,7 +99,7 @@
<logger name="*.SqlSugar.SqlSugarSetup" final="true" writeTo="consoleSql,sqlfile"/> <logger name="*.SqlSugar.SqlSugarSetup" final="true" writeTo="consoleSql,sqlfile"/>
<logger name="*" minLevel="Trace" writeTo="allfile" /> <logger name="*" minLevel="Trace" writeTo="allfile" />
<logger name="*.GlobalExceptionMiddleware" final="true" writeTo="consoleSql,errorfile"/> <logger name="*.GlobalExceptionMiddleware" final="true" writeTo="consoleSql,errorfile"/>
<logger name="ZR.Admin.WebApi.Middleware.CustomIpRateLimitMiddleware" final="true" writeTo="ipRateLimit" /> <logger name="ZR.Admin.WebApi.Middleware.CustomIpRateLimitMiddleware" final="true" writeTo="consoleIpRateLimit,ipRateLimitFile" />
<!--Skip non-critical Microsoft logs and so log only own logs--> <!--Skip non-critical Microsoft logs and so log only own logs-->
<logger name="Microsoft.*,Quartz.Core.QuartzSchedulerThread" maxlevel="Info" final="true" /> <logger name="Microsoft.*,Quartz.Core.QuartzSchedulerThread" maxlevel="Info" final="true" />
</rules> </rules>

View File

@ -19,6 +19,9 @@ using IpRateLimitPolicy = AspNetCoreRateLimit.IpRateLimitPolicy;
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
//load json config by ipRateLimit
builder.Configuration.AddJsonFile("IpRateLimitConfig.json", true, true);
//load json config by loginVerify //load json config by loginVerify
builder.Configuration.AddJsonFile("loginVerifyConf.json", true, true); builder.Configuration.AddJsonFile("loginVerifyConf.json", true, true);
@ -38,7 +41,7 @@ builder.Services.AddCors(builder.Configuration);
// Grpc // Grpc
builder.Services.AddGrpc(); builder.Services.AddGrpc();
// 显示logo // 显示logo
// builder.Services.AddLogo(); builder.Services.AddLogo();
//消除Error unprotecting the session cookie警告 //消除Error unprotecting the session cookie警告
builder.Services.AddDataProtection() builder.Services.AddDataProtection()
.PersistKeysToFileSystem(new DirectoryInfo(Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + "DataProtection")); .PersistKeysToFileSystem(new DirectoryInfo(Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + "DataProtection"));

View File

@ -103,35 +103,9 @@
"RedisServer": { "RedisServer": {
"open": 1, //redis "open": 1, //redis
"Cache": "8.140.174.251:6379,password=Wyd210213,defaultDatabase=0,poolsize=50,ssl=false,writeBuffer=10240,prefix=cache:", "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": "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:"
//
"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
},
//api,*
"GeneralRules": [
{
"Endpoint": "*:/captchaImage",
//{}{}使s, m, h, d
"Period": "3s",
"Limit": 5
},
{
"Endpoint": "((post)|(put)):*",
"Period": "3s",
"Limit": 1
}
]
}, },
// //
"CaptchaOptions": { "CaptchaOptions": {
@ -147,5 +121,8 @@
"BubbleCount": 3, // "BubbleCount": 3, //
"BubbleThickness": 1.0 // 沿 "BubbleThickness": 1.0 // 沿
} }
},
"GrpcUrls": {
"FindTeacher": "http://localhost:5212"
} }
} }

View 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>

269
ZR.Common/IdUtils.cs Normal file
View 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; }
}

View File

@ -12,7 +12,5 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="Mapster" Version="7.3.0" /> <PackageReference Include="Mapster" Version="7.3.0" />
<PackageReference Include="MySqlConnector" Version="2.2.6" /> <PackageReference Include="MySqlConnector" Version="2.2.6" />
<PackageReference Include="SqlSugar.IOC" Version="2.0.0" />
<PackageReference Include="SqlSugarCoreNoDrive" Version="5.1.4.109" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View 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; }
}

View File

@ -15,6 +15,7 @@ namespace ZR.ServiceCore.Model.Dto
public string NoticeContent { get; set; } public string NoticeContent { get; set; }
public int Status { get; set; } public int Status { get; set; }
public string Remark { get; set; } public string Remark { get; set; }
public string Create_name { get; set; }
public DateTime Create_time { get; set; } public DateTime Create_time { get; set; }
} }

View File

@ -39,9 +39,13 @@
/// </summary> /// </summary>
public string FileExt { get; set; } public string FileExt { get; set; }
/// <summary> /// <summary>
/// 创建 /// 创建
/// </summary> /// </summary>
public string Create_by { get; set; } public long Create_by { get; set; }
/// <summary>
/// 创建者名称
/// </summary>
public string Create_name { get; set; }
/// <summary> /// <summary>
/// 上传时间 /// 上传时间
/// </summary> /// </summary>
@ -56,14 +60,16 @@
public string AccessUrl { get; set; } public string AccessUrl { get; set; }
public SysFile() { } public SysFile() { }
public SysFile(string originFileName, string fileName, string ext, string fileSize, string storePath, string create_by) public SysFile(string originFileName, string fileName, string ext, string fileSize, string storePath,
long createBy, string createName)
{ {
StorePath = storePath; StorePath = storePath;
RealName = originFileName; RealName = originFileName;
FileName = fileName; FileName = fileName;
FileExt = ext; FileExt = ext;
FileSize = fileSize; FileSize = fileSize;
Create_by = create_by; Create_by = createBy;
Create_name = createName;
Create_time = DateTime.Now; Create_time = DateTime.Now;
} }
} }

View File

@ -0,0 +1,33 @@
using Infrastructure.Attribute;
using ZR.Model;
using ZR.Model.System;
using ZR.Service;
using ZR.Service.System.IService;
using ZR.ServiceCore.Services.IService;
namespace ZR.ServiceCore.Services;
[AppService(ServiceType = typeof(IBaseCodeRuleService), ServiceLifetime = LifeTime.Transient)]
public class BaseCodeRuleService : BaseService<BaseCodeRule>, IBaseCodeRuleService
{
public Task<int> InsertBaseCodeRuleAsync(BaseCodeRule baseCodeRule)
{
return Insertable(baseCodeRule).ExecuteCommandAsync();
}
public Task<int> DeleteBaseCodeRuleAsync(string code)
{
return Deleteable().Where(m => m.Code == code).ExecuteCommandAsync();
}
public Task<int> UpdateBaseCodeRule(BaseCodeRule baseCodeRule)
{
return Updateable(baseCodeRule).ExecuteCommandAsync();
}
public PagedInfo<BaseCodeRule> SelectBaseCodeRulePage(BaseCodeRule baseCodeRule, PagerInfo pager)
{
var exp = Expressionable.Create<BaseCodeRule>();
return GetPages(exp.ToExpression(), pager);
}
}

View File

@ -0,0 +1,16 @@
using ZR.Model;
using ZR.Model.System;
using ZR.Service;
namespace ZR.ServiceCore.Services.IService;
public interface IBaseCodeRuleService : IBaseService<BaseCodeRule>
{
public Task<int> InsertBaseCodeRuleAsync(BaseCodeRule baseCodeRule);
public Task<int> DeleteBaseCodeRuleAsync(string code);
public Task<int> UpdateBaseCodeRule(BaseCodeRule baseCodeRule);
public PagedInfo<BaseCodeRule> SelectBaseCodeRulePage(BaseCodeRule baseCodeRule, PagerInfo pager);
}

View File

@ -1,10 +1,8 @@
using Infrastructure.Attribute; using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http; using ZR.Service;
using System.Threading.Tasks;
using ZR.Model.System;
using ZR.ServiceCore.Model; using ZR.ServiceCore.Model;
namespace ZR.Service.System.IService namespace ZR.ServiceCore.Services.IService
{ {
public interface ISysFileService : IBaseService<SysFile> public interface ISysFileService : IBaseService<SysFile>
{ {
@ -19,7 +17,8 @@ namespace ZR.Service.System.IService
/// <param name="rootPath"></param> /// <param name="rootPath"></param>
/// <param name="userName"></param> /// <param name="userName"></param>
/// <returns>文件对象</returns> /// <returns>文件对象</returns>
Task<SysFile> SaveFileToLocal(string rootPath, string fileName, string fileDir, string userName, IFormFile formFile, string uploadUrl); Task<SysFile> SaveFileToLocal(string rootPath, string fileName, string fileDir, long userId, string userName,
IFormFile formFile, string uploadUrl);
Task<SysFile> SaveFileToAliyun(SysFile file, IFormFile formFile); Task<SysFile> SaveFileToAliyun(SysFile file, IFormFile formFile);
/// <summary> /// <summary>

View File

@ -1,18 +1,19 @@
using Infrastructure; using System.Net;
using System.Security.Cryptography;
using System.Text;
using Infrastructure;
using Infrastructure.Attribute; using Infrastructure.Attribute;
using Infrastructure.Enums; using Infrastructure.Enums;
using Infrastructure.Model; using Infrastructure.Model;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using ZR.Common; using ZR.Common;
using ZR.Model.System; using ZR.Service;
using ZR.Service.System.IService; using ZR.Service.System.IService;
using ZR.ServiceCore.Model; using ZR.ServiceCore.Model;
using ZR.ServiceCore.Services.IService;
namespace ZR.Service.System namespace ZR.ServiceCore.Services
{ {
/// <summary> /// <summary>
/// 文件管理 /// 文件管理
@ -38,7 +39,8 @@ namespace ZR.Service.System
/// <param name="formFile">上传的文件流</param> /// <param name="formFile">上传的文件流</param>
/// <param name="userName"></param> /// <param name="userName"></param>
/// <returns></returns> /// <returns></returns>
public async Task<SysFile> SaveFileToLocal(string rootPath, string fileName, string fileDir, string userName, IFormFile formFile, string uploadUrl) public async Task<SysFile> SaveFileToLocal(string rootPath, string fileName, string fileDir, long userId, string userName,
IFormFile formFile, string uploadUrl)
{ {
string fileExt = Path.GetExtension(formFile.FileName); string fileExt = Path.GetExtension(formFile.FileName);
fileName = (fileName.IsEmpty() ? HashFileName() : fileName) + fileExt; fileName = (fileName.IsEmpty() ? HashFileName() : fileName) + fileExt;
@ -58,7 +60,7 @@ namespace ZR.Service.System
} }
// string uploadUrl = OptionsSetting.Upload.UploadUrl; // string uploadUrl = OptionsSetting.Upload.UploadUrl;
string accessPath = string.Concat(uploadUrl, "/", filePath.Replace("\\", "/"), "/", fileName); string accessPath = string.Concat(uploadUrl, "/", filePath.Replace("\\", "/"), "/", fileName);
SysFile file = new(formFile.FileName, fileName, fileExt, fileSize + "kb", filePath, userName) SysFile file = new(formFile.FileName, fileName, fileExt, fileSize + "kb", filePath, userId, userName)
{ {
StoreType = (int)StoreType.LOCAL, StoreType = (int)StoreType.LOCAL,
FileType = formFile.ContentType, FileType = formFile.ContentType,