:recycle:代码重构

This commit is contained in:
不做码农
2023-09-02 17:55:34 +08:00
parent c65952202a
commit be515339fe
176 changed files with 372 additions and 245 deletions
+150
View File
@@ -0,0 +1,150 @@
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Collections;
using System.Reflection;
namespace ZR.Common
{
public class CacheHelper
{
public static MemoryCache Cache { get; set; }
static CacheHelper()
{
Cache = new MemoryCache(new MemoryCacheOptions
{
//SizeLimit = 1024
});
}
/// <summary>
/// 获取缓存
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public static T GetCache<T>(string key) where T : class
{
if (key == null)
throw new ArgumentNullException(nameof(key));
//return Cache.Get(key) as T; //或者
return Cache.Get<T>(key);
}
/// <summary>
/// 获取缓存
/// </summary>
/// <param name="CacheKey"></param>
/// <returns></returns>
public static object GetCache(string CacheKey)
{
return Cache.Get<object>(CacheKey);
}
public static object Get(string CacheKey)
{
return Cache.Get(CacheKey);
}
/// <summary>
/// 设置缓存,永久缓存
/// </summary>
/// <param name="CacheKey">key</param>
/// <param name="objObject">值</param>
public static object SetCache(string CacheKey, object objObject)
{
return Cache.Set(CacheKey, objObject);
}
/// <summary>
/// 设置缓存
/// </summary>
/// <param name="CacheKey">key</param>
/// <param name="objObject">值</param>
/// <param name="Timeout">过期时间(分钟)</param>
public static object SetCache(string CacheKey, object objObject, int Timeout)
{
return Cache.Set(CacheKey, objObject, DateTime.Now.AddMinutes(Timeout));
}
/// <summary>
/// 设置缓存(秒)
/// </summary>
/// <param name="CacheKey">key</param>
/// <param name="objObject">值</param>
/// <param name="Timeout">过期时间(秒)</param>
public static void SetCaches(string CacheKey, object objObject, int Timeout)
{
Cache.Set(CacheKey, objObject, DateTime.Now.AddSeconds(Timeout));
}
/// <summary>
/// 设置缓存
/// </summary>
/// <param name="CacheKey">key</param>
/// <param name="objObject">值</param>
/// <param name="absoluteExpiration">过期时间</param>
/// <param name="slidingExpiration">过期时间间隔</param>
public static object SetCache(string CacheKey, object objObject, DateTime absoluteExpiration, TimeSpan slidingExpiration)
{
return Cache.Set(CacheKey, objObject, absoluteExpiration);
}
/// <summary>
/// 设定绝对的过期时间
/// </summary>
/// <param name="CacheKey"></param>
/// <param name="objObject"></param>
/// <param name="Seconds">超过多少秒后过期</param>
public static void SetCacheDateTime(string CacheKey, object objObject, long Seconds)
{
Cache.Set(CacheKey, objObject, DateTime.Now.AddSeconds(Seconds));
}
/// <summary>
/// 删除缓存
/// </summary>
/// <param name="key">key</param>
public static void Remove(string key)
{
Cache.Remove(key);
}
/// <summary>
/// 验证缓存项是否存在
/// </summary>
/// <param name="key">缓存Key</param>
/// <returns></returns>
public static bool Exists(string key)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
return Cache.TryGetValue(key, out _);
}
/// <summary>
/// 获取所有缓存键
/// </summary>
/// <returns></returns>
public static List<string> GetCacheKeys()
{
const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
//var entries = Cache.GetType().GetField("_entries", flags).GetValue(Cache);
//.net7需要这样写
var coherentState = Cache.GetType().GetField("_coherentState", flags).GetValue(Cache);
var entries = coherentState.GetType().GetField("_entries", flags).GetValue(coherentState);
var keys = new List<string>();
if (entries is not IDictionary cacheItems) return keys;
foreach (DictionaryEntry cacheItem in cacheItems)
{
keys.Add(cacheItem.Key.ToString());
//Console.WriteLine("缓存key=" +cacheItem.Key);
}
return keys;
}
}
}
+17
View File
@@ -0,0 +1,17 @@
using CSRedis;
using Infrastructure;
namespace ZR.Common.Cache
{
public class RedisServer
{
public static CSRedisClient Cache;
public static CSRedisClient Session;
public static void Initalize()
{
Cache = new CSRedisClient(AppSettings.GetConfig("RedisServer:Cache"));
Session = new CSRedisClient(AppSettings.GetConfig("RedisServer:Session"));
}
}
}
@@ -0,0 +1,209 @@
using Infrastructure.Extensions;
using Infrastructure.Model;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using MiniExcelLibs;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
namespace Infrastructure.Controllers
{
public class BaseController : ControllerBase
{
public static string TIME_FORMAT_FULL = "yyyy-MM-dd HH:mm:ss";
/// <summary>
/// 返回成功封装
/// </summary>
/// <param name="data"></param>
/// <param name="timeFormatStr"></param>
/// <returns></returns>
protected IActionResult SUCCESS(object data, string timeFormatStr = "yyyy-MM-dd HH:mm:ss")
{
string jsonStr = GetJsonStr(GetApiResult(data != null ? ResultCode.SUCCESS : ResultCode.NO_DATA, data), timeFormatStr);
return Content(jsonStr, "application/json");
}
/// <summary>
/// json输出带时间格式的
/// </summary>
/// <param name="apiResult"></param>
/// <returns></returns>
protected IActionResult ToResponse(ApiResult apiResult)
{
string jsonStr = GetJsonStr(apiResult, TIME_FORMAT_FULL);
return Content(jsonStr, "application/json");
}
protected IActionResult ToResponse(long rows, string timeFormatStr = "yyyy-MM-dd HH:mm:ss")
{
string jsonStr = GetJsonStr(ToJson(rows), timeFormatStr);
return Content(jsonStr, "application/json");
}
protected IActionResult ToResponse(ResultCode resultCode, string msg = "")
{
return ToResponse(new ApiResult((int)resultCode, msg));
}
/// <summary>
/// 导出Excel
/// </summary>
/// <param name="path">完整文件路径</param>
/// <param name="fileName">带扩展文件名</param>
/// <returns></returns>
protected IActionResult ExportExcel(string path, string fileName)
{
//var webHostEnvironment = App.WebHostEnvironment;
if (!Path.Exists(path))
{
throw new CustomException(fileName + "文件不存在");
}
var stream = System.IO.File.OpenRead(path); //创建文件流
Response.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");
return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", HttpUtility.UrlEncode(fileName));
}
#region 方法
/// <summary>
/// 响应返回结果
/// </summary>
/// <param name="rows">受影响行数</param>
/// <param name="data"></param>
/// <returns></returns>
protected ApiResult ToJson(long rows, object? data = null)
{
return rows > 0 ? ApiResult.Success("success", data) : GetApiResult(ResultCode.FAIL);
}
/// <summary>
/// 全局Code使用
/// </summary>
/// <param name="resultCode"></param>
/// <param name="data"></param>
/// <returns></returns>
protected ApiResult GetApiResult(ResultCode resultCode, object? data = null)
{
var msg = resultCode.GetDescription();
return new ApiResult((int)resultCode, msg, data);
}
/// <summary>
///
/// </summary>
/// <param name="apiResult"></param>
/// <param name="timeFormatStr"></param>
/// <returns></returns>
private static string GetJsonStr(ApiResult apiResult, string timeFormatStr)
{
if (string.IsNullOrEmpty(timeFormatStr))
{
timeFormatStr = TIME_FORMAT_FULL;
}
var serializerSettings = new JsonSerializerSettings
{
// 设置为驼峰命名
ContractResolver = new CamelCasePropertyNamesContractResolver(),
DateFormatString = timeFormatStr
};
return JsonConvert.SerializeObject(apiResult, Formatting.Indented, serializerSettings);
}
#endregion
/// <summary>
/// 导出Excel
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <param name="sheetName"></param>
/// <param name="fileName"></param>
protected string ExportExcel<T>(List<T> list, string sheetName, string fileName)
{
return ExportExcelMini(list, sheetName, fileName).Item1;
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <param name="sheetName"></param>
/// <param name="fileName"></param>
/// <returns></returns>
protected (string, string) ExportExcelMini<T>(List<T> list, string sheetName, string fileName)
{
IWebHostEnvironment webHostEnvironment = (IWebHostEnvironment)App.ServiceProvider.GetService(typeof(IWebHostEnvironment));
string sFileName = $"{fileName}{DateTime.Now:MM-dd-HHmmss}.xlsx";
string fullPath = Path.Combine(webHostEnvironment.WebRootPath, "export", sFileName);
Directory.CreateDirectory(Path.GetDirectoryName(fullPath));
MiniExcel.SaveAs(fullPath, list, sheetName: sheetName);
return (sFileName, fullPath);
}
/// <summary>
/// 导出多个工作表(Sheet)
/// </summary>
/// <param name="sheets"></param>
/// <param name="fileName"></param>
/// <returns></returns>
protected (string, string) ExportExcelMini(Dictionary<string, object> sheets, string fileName)
{
IWebHostEnvironment webHostEnvironment = (IWebHostEnvironment)App.ServiceProvider.GetService(typeof(IWebHostEnvironment));
string sFileName = $"{fileName}{DateTime.Now:MM-dd-HHmmss}.xlsx";
string fullPath = Path.Combine(webHostEnvironment.WebRootPath, "export", sFileName);
Directory.CreateDirectory(Path.GetDirectoryName(fullPath));
MiniExcel.SaveAs(fullPath, sheets);
return (sFileName, fullPath);
}
/// <summary>
/// 下载导入模板
/// </summary>
/// <typeparam name="T">数据类型</typeparam>
/// <param name="list">空数据类型集合</param>
/// <param name="fileName">下载文件名</param>
/// <returns></returns>
protected (string, string) DownloadImportTemplate<T>(List<T> list, string fileName)
{
IWebHostEnvironment webHostEnvironment = App.WebHostEnvironment;
string sFileName = $"{fileName}.xlsx";
string fullPath = Path.Combine(webHostEnvironment.WebRootPath, "ImportTemplate", sFileName);
//不存在模板创建模板
if (!Directory.Exists(fullPath))
{
Directory.CreateDirectory(Path.GetDirectoryName(fullPath));
MiniExcel.SaveAs(fullPath, list, overwriteFile: true);
}
return (sFileName, fullPath);
}
/// <summary>
/// 下载指定文件模板
/// </summary>
/// <param name="fileName">下载文件名</param>
/// <returns></returns>
protected (string, string) DownloadImportTemplate(string fileName)
{
IWebHostEnvironment webHostEnvironment = (IWebHostEnvironment)App.ServiceProvider.GetService(typeof(IWebHostEnvironment));
string sFileName = $"{fileName}.xlsx";
string fullPath = Path.Combine(webHostEnvironment.WebRootPath, "ImportTemplate", sFileName);
return (sFileName, fullPath);
}
}
}
@@ -2,7 +2,7 @@
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Infrastructure
namespace Infrastructure.Converter
{
public class JsonConverterUtil
{
@@ -4,7 +4,7 @@ using System.Linq;
using System.Text;
using System.Text.Json;
namespace Infrastructure
namespace Infrastructure.Converter
{
/// <summary>
/// Json任何类型读取到字符串属性
@@ -33,10 +33,10 @@ namespace Infrastructure
writer.WriteStringValue(value);
}
/// <summary>
/// 非字符类型,返回原生内容
/// </summary>
/// <param name="jsonReader"></param>
/// <returns></returns>
/// 非字符类型,返回原生内容
/// </summary>
/// <param name="jsonReader"></param>
/// <returns></returns>
private static string GetRawPropertyValue(Utf8JsonReader jsonReader)
{
ReadOnlySpan<byte> utf8Bytes = jsonReader.HasValueSequence ?
+5
View File
@@ -54,5 +54,10 @@
/// 清空数据
/// </summary>
CLEAN = 9,
/// <summary>
/// 下载
/// </summary>
DOWNLOAD = 10,
}
}
+28
View File
@@ -0,0 +1,28 @@
using JinianNet.JNTemplate;
using System;
using System.IO;
namespace Infrastructure.Helper
{
public class JnHelper
{
/// <summary>
/// 读取Jn模板
/// </summary>
/// <param name="dirPath"></param>
/// <param name="tplName"></param>
/// <returns></returns>
public static ITemplate ReadTemplate(string dirPath, string tplName)
{
string path = Environment.CurrentDirectory;
string fullName = Path.Combine(path, "wwwroot", dirPath, tplName);
if (File.Exists(fullName))
{
return Engine.LoadTemplate(fullName);
}
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"未找到路径{fullName}");
return null;
}
}
}
-1
View File
@@ -1,6 +1,5 @@
using Infrastructure.Extensions;
using Infrastructure.Model;
using Infrastructure.WebExtensins;
using Microsoft.AspNetCore.Http;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
+4
View File
@@ -15,6 +15,10 @@ namespace Infrastructure.Model
/// 是否演示模式
/// </summary>
public bool DemoMode { get; set; }
/// <summary>
/// 初始化db
/// </summary>
public bool InitDb { get; set; }
public MailOptions MailOptions { get; set; }
public Upload Upload { get; set; }
public ALIYUN_OSS ALIYUN_OSS { get; set; }
@@ -0,0 +1,34 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
namespace Infrastructure
{
/// <summary>
/// 跨域扩展
/// </summary>
public static class CorsExtension
{
/// <summary>
/// 跨域配置
/// </summary>
/// <param name="services"></param>
/// <param name="configuration"></param>
public static void AddCors(this IServiceCollection services, IConfiguration configuration)
{
var corsUrls = configuration.GetSection("corsUrls").Get<string[]>();
//配置跨域
services.AddCors(c =>
{
c.AddPolicy("Policy", policy =>
{
policy.WithOrigins(corsUrls ?? Array.Empty<string>())
.AllowAnyHeader()//允许任意头
.AllowCredentials()//允许cookie
.AllowAnyMethod();//允许任意方法
});
});
}
}
}
@@ -0,0 +1,41 @@
using Infrastructure.Extensions;
using Microsoft.AspNetCore.Http;
using System;
using System.Reflection;
namespace Infrastructure
{
public static class EntityExtension
{
public static TSource ToCreate<TSource>(this TSource source, HttpContext? context = null)
{
var types = source?.GetType();
if (types == null) return source;
BindingFlags flag = BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.Instance;
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("UserId", flag)?.SetValue(source, context.GetUId(), null);
return source;
}
public static TSource ToUpdate<TSource>(this TSource source, HttpContext? context = null)
{
var types = source?.GetType();
if (types == null) return source;
BindingFlags flag = BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.Instance;
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);
return source;
}
}
}
@@ -1,5 +1,4 @@
using Infrastructure.Extensions;
using IPTools.Core;
using IPTools.Core;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
@@ -10,7 +9,7 @@ using System.Text;
using System.Text.RegularExpressions;
using UAParser;
namespace Infrastructure.WebExtensins
namespace Infrastructure.Extensions
{
/// <summary>
/// HttpContext扩展类
@@ -220,7 +219,8 @@ namespace Infrastructure.WebExtensins
if (HttpMethods.IsPost(reqMethod) || HttpMethods.IsPut(reqMethod) || HttpMethods.IsDelete(reqMethod))
{
param = context.GetBody();
param = PwdRep().Replace(param, "***");
string regex = "(?<=\"password\":\")[^\",]*";
param = Regex.Replace(param, regex, "***");
}
if (param.IsEmpty())
{
@@ -228,9 +228,6 @@ namespace Infrastructure.WebExtensins
}
return param;
}
[GeneratedRegex("(?<=\"password\":\")[^\",]*")]
private static partial Regex PwdRep();
}
}
@@ -0,0 +1,27 @@
using AspNetCoreRateLimit;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
namespace ZR.Infrastructure.WebExtensions
{
public static class IPRateExtension
{
public static void AddIPRate(this IServiceCollection services, IConfiguration configuration)
{
if (services == null) throw new ArgumentNullException(nameof(services));
//从appsettings.json中加载常规配置,IpRateLimiting与配置文件中节点对应
services.Configure<IpRateLimitOptions>(configuration.GetSection("IpRateLimiting"));
//从appsettings.json中加载Ip规则
services.Configure<IpRateLimitPolicies>(configuration.GetSection("IpRateLimitPolicies"));
//注入计数器和规则存储
services.AddSingleton<IIpPolicyStore, MemoryCacheIpPolicyStore>();
services.AddSingleton<IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>();
//配置(解析器、计数器密钥生成器)
services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();
services.AddSingleton<IProcessingStrategy, AsyncKeyLockProcessingStrategy>();
}
}
}
@@ -0,0 +1,24 @@
using Infrastructure.Helper;
using JinianNet.JNTemplate;
using Microsoft.Extensions.DependencyInjection;
using System;
namespace Infrastructure
{
public static class LogoExtension
{
public static void AddLogo(this IServiceCollection services)
{
Console.ForegroundColor = ConsoleColor.Blue;
var contentTpl = JnHelper.ReadTemplate("", "logo.txt");
var content = contentTpl?.Render();
Console.WriteLine(content);
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine("🎉源码地址: https://gitee.com/izory/ZrAdminNetCore");
Console.WriteLine("📖官方文档:http://www.izhaorui.cn/doc");
Console.WriteLine("💰打赏作者:http://www.izhaorui.cn/doc/support.html");
Console.WriteLine("📱移动端体验:http://www.izhaorui.cn/h5");
}
}
}
@@ -8,18 +8,19 @@
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
<Compile Remove="Model\PagedInfo.cs" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="AspectCore.Abstractions" Version="2.4.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="7.0.4" />
<PackageReference Include="Microsoft.Extensions.DependencyModel" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="7.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<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" />
<PackageReference Include="JinianNet.JNTemplate" Version="2.3.3" />
<PackageReference Include="MiniExcel" Version="1.31.2" />
<PackageReference Include="CSRedisCore" Version="3.8.670" />
<PackageReference Include="AspNetCoreRateLimit" Version="5.0.0" />
</ItemGroup>
</Project>