🍒 feat: 迁移远程请求服务配置到Core层,优化自定义序列化

This commit is contained in:
喵你个汪呀 2025-08-27 08:39:18 +08:00
parent 90468581fa
commit fc748272a5
10 changed files with 230 additions and 378 deletions

View File

@ -1,92 +0,0 @@
// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证(版本 2.0)进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动!任何基于本项目二次开发而产生的一切法律纠纷和责任,我们不承担任何责任!
namespace Admin.NET.Core;
/// <summary>
/// 通用接口参数验证特性类
/// </summary>
[AttributeUsage(AttributeTargets.Property)]
public class CommonValidationAttribute : ValidationAttribute
{
private readonly Dictionary<string, string> _conditions;
private static readonly Dictionary<string, Delegate> CompiledConditions = [];
/// <summary>
/// </summary>
/// <param name="conditionPairs">条件对参数,长度必须为偶数<br/>
/// 奇数字符串参数:动态条件<br/>
/// 偶数字符串参数:提示消息
/// </param>
/// <example>
/// <code lang="C">
/// public class ModelInput {
///
///
/// public string A { get; set; }
///
///
/// [CommonValidation(
/// "A == 1 <value>&amp;&amp;</value> B == null", "当 A == 1时B不能为空",
/// "C == 2 <value>&amp;&amp;</value> B == null", "当 C == 2时B不能为空"
/// )]
/// public string B { get; set; }
/// }
/// </code>
/// </example>
public CommonValidationAttribute(params string[] conditionPairs)
{
if (conditionPairs.Length % 2 != 0) throw new ArgumentException("条件对必须以偶数个字符串的形式提供。");
var conditions = new Dictionary<string, string>();
for (int i = 0; i < conditionPairs.Length; i += 2)
conditions.Add(conditionPairs[i], conditionPairs[i + 1]);
_conditions = conditions;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
foreach (var (expr, errorMessage) in _conditions)
{
var conditionKey = $"{validationContext.ObjectType.FullName}.{expr}";
if (!CompiledConditions.TryGetValue(conditionKey, out var condition))
{
condition = CreateCondition(validationContext.ObjectType, expr);
CompiledConditions[conditionKey] = condition;
}
if ((bool)condition.DynamicInvoke(validationContext.ObjectInstance)!)
{
return new ValidationResult(errorMessage ?? $"[{validationContext.MemberName}]校验失败");
}
}
return ValidationResult.Success;
}
private Delegate CreateCondition(Type modelType, string expression)
{
try
{
// 创建参数表达式
var parameter = Expression.Parameter(typeof(object), "x");
// 构建 Lambda 表达式
var lambda = DynamicExpressionParser.ParseLambda([Expression.Parameter(modelType, "x")], typeof(bool), expression);
// 创建新的 Lambda 表达式,接受 object 参数并调用编译后的表达式
var invokeExpression = Expression.Invoke(lambda, Expression.Convert(parameter, modelType));
var finalLambda = Expression.Lambda<Func<object, bool>>(invokeExpression, parameter);
return finalLambda.Compile();
}
catch (Exception ex)
{
throw new ArgumentException($"无法解析表达式 '{expression}': {ex.Message}", ex);
}
}
}

View File

@ -1,21 +0,0 @@
// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证(版本 2.0)进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动!任何基于本项目二次开发而产生的一切法律纠纷和责任,我们不承担任何责任!
namespace Admin.NET.Core;
/// <summary>
/// 自定义规范化结果特性
/// </summary>
[AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = true)]
public class CustomUnifyResultAttribute : Attribute
{
public string Name { get; set; }
public CustomUnifyResultAttribute(string name)
{
Name = name;
}
}

View File

@ -9,8 +9,7 @@ namespace Admin.NET.Core;
/// <summary>
/// Http远程服务扩展
/// </summary>
public static class HttpRemotesExtension
{
public static class HttpRemotesExtension {
/// <summary>
/// 添加Http远程服务
/// </summary>
@ -23,13 +22,12 @@ public static class HttpRemotesExtension
{
if (prop.GetValue(options) is not HttpRemoteItem opt) continue;
services.AddHttpClient(opt.HttpName, client =>
{
client.BaseAddress = new Uri(opt.BaseAddress);
client.Timeout = TimeSpan.FromSeconds(opt.Timeout);
foreach (var kv in opt.Headers) client.DefaultRequestHeaders.Add(kv.Key, kv.Value);
})
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
{
client.BaseAddress = new Uri(opt.BaseAddress);
client.Timeout = TimeSpan.FromSeconds(opt.Timeout);
foreach (var kv in opt.Headers) client.DefaultRequestHeaders.Add(kv.Key, kv.Value);
})
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler {
UseCookies = opt.UseCookies
})
.AddHttpMessageHandler<HttpLoggingHandler>();

View File

@ -4,6 +4,8 @@
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动!任何基于本项目二次开发而产生的一切法律纠纷和责任,我们不承担任何责任!
using System.Text.Json;
namespace Admin.NET.Core;
/// <summary>
@ -351,4 +353,16 @@ public static partial class ObjectExtension
return obj;
}
/// <summary>
/// 对象转为自定义JSON字符串
/// </summary>
public static string ToCustomJson<T>(this T obj, JsonSerializerOptions options = null)
=> CustomJsonHelper.Serialize(obj, options);
/// <summary>
/// 自定义JSON字符串转为对象
/// </summary>
public static T FromCustomJson<T>(this string json, JsonSerializerOptions options = null)
=> CustomJsonHelper.Deserialize<T>(json, options);
}

View File

@ -12,7 +12,7 @@ namespace Admin.NET.Core;
public sealed class HttpRemotesOptions : IConfigurableOptions
{
/// <summary>
/// 企业微信
/// 企业微信
/// </summary>
public HttpRemoteItem WorkWeixin { get; set; }
}

View File

@ -0,0 +1,158 @@
// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证(版本 2.0)进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动!任何基于本项目二次开发而产生的一切法律纠纷和责任,我们不承担任何责任!
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Admin.NET.Core;
/// <summary>
/// 自定义JSON转换器
/// </summary>
/// <summary>
/// 自定义JSON转换器工厂类
/// </summary>
public class CustomJsonConverter : JsonConverterFactory
{
/// <summary>
/// 判断是否可以转换指定类型
/// </summary>
/// <param name="typeToConvert">要转换的类型</param>
/// <returns>是否可以转换</returns>
public override bool CanConvert(Type typeToConvert)
{
return typeToConvert.GetProperties()
.Any(p => p.GetCustomAttribute<CustomJsonPropertyAttribute>() != null);
}
/// <summary>
/// 创建指定类型的转换器实例
/// </summary>
/// <param name="type">要转换的类型</param>
/// <param name="options">JSON序列化选项</param>
/// <returns>JSON转换器实例</returns>
public override JsonConverter CreateConverter(Type type, JsonSerializerOptions options)
{
var converterType = typeof(CustomConverter<>).MakeGenericType(type);
return (JsonConverter)Activator.CreateInstance(converterType, options);
}
/// <summary>
/// 自定义转换器实现类
/// </summary>
/// <typeparam name="T">要转换的类型</typeparam>
private class CustomConverter<T> : JsonConverter<T>
{
/// <summary>
/// 基础JSON序列化选项
/// </summary>
private readonly JsonSerializerOptions _baseOptions;
/// <summary>
/// JSON属性名到对象属性的映射字典
/// </summary>
private readonly Dictionary<string, PropertyInfo> _jsonToPropertyMap;
/// <summary>
/// 构造函数
/// </summary>
/// <param name="baseOptions">基础JSON序列化选项</param>
public CustomConverter(JsonSerializerOptions baseOptions)
{
_baseOptions = new JsonSerializerOptions(baseOptions);
_jsonToPropertyMap = CreatePropertyMap();
}
/// <summary>
/// 创建属性映射字典
/// </summary>
/// <returns>属性映射字典</returns>
private Dictionary<string, PropertyInfo> CreatePropertyMap()
{
var map = new Dictionary<string, PropertyInfo>(StringComparer.OrdinalIgnoreCase);
foreach (var prop in typeof(T).GetProperties())
{
var customAttr = prop.GetCustomAttribute<CustomJsonPropertyAttribute>();
if (customAttr != null)
{
map[customAttr.Name] = prop;
}
else
{
var jsonName = _baseOptions.PropertyNamingPolicy?.ConvertName(prop.Name) ?? prop.Name;
map[jsonName] = prop;
}
}
return map;
}
/// <summary>
/// 反序列化JSON为对象
/// </summary>
/// <param name="reader">JSON读取器</param>
/// <param name="typeToConvert">要转换的类型</param>
/// <param name="options">JSON序列化选项</param>
/// <returns>反序列化后的对象</returns>
public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType == JsonTokenType.Null) return default;
// 创建实例并设置默认值
var instance = Activator.CreateInstance<T>();
object GetDefaultValue(Type type) => type.IsValueType ? Activator.CreateInstance(type) : null;
foreach (var prop in typeof(T).GetProperties().Where(p => p.CanWrite))
prop.SetValue(instance, GetDefaultValue(prop.PropertyType));
while (reader.Read() && reader.TokenType != JsonTokenType.EndObject)
{
if (reader.TokenType == JsonTokenType.PropertyName)
{
var propertyName = reader.GetString();
if (_jsonToPropertyMap.TryGetValue(propertyName, out var prop))
{
reader.Read();
var value = JsonSerializer.Deserialize(ref reader, prop.PropertyType, _baseOptions);
prop.SetValue(instance, value);
}
else
{
reader.Skip();
}
}
}
return instance;
}
/// <summary>
/// 序列化对象为JSON
/// </summary>
/// <param name="writer">JSON写入器</param>
/// <param name="value">要序列化的对象</param>
/// <param name="options">JSON序列化选项</param>
public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
{
writer.WriteStartObject();
foreach (var prop in typeof(T).GetProperties())
{
var propValue = prop.GetValue(value);
if (propValue == null && _baseOptions.DefaultIgnoreCondition == JsonIgnoreCondition.WhenWritingNull)
continue;
var customAttr = prop.GetCustomAttribute<CustomJsonPropertyAttribute>();
var jsonName = customAttr?.Name ?? _baseOptions.PropertyNamingPolicy?.ConvertName(prop.Name) ?? prop.Name;
writer.WritePropertyName(jsonName);
JsonSerializer.Serialize(writer, propValue, prop.PropertyType, _baseOptions);
}
writer.WriteEndObject();
}
}
}

View File

@ -0,0 +1,46 @@
// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证(版本 2.0)进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动!任何基于本项目二次开发而产生的一切法律纠纷和责任,我们不承担任何责任!
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Admin.NET.Core;
/// <summary>
/// 自定义Json序列化工具
/// </summary>
public static class CustomJsonHelper
{
/// <summary>
/// 序列化对象
/// </summary>
public static string Serialize(object obj, JsonSerializerOptions globalOptions = null)
{
var options = CreateOptions(globalOptions);
return JsonSerializer.Serialize(obj, options);
}
/// <summary>
/// 反序列化对象
/// </summary>
public static T Deserialize<T>(string json, JsonSerializerOptions globalOptions = null)
{
var options = CreateOptions(globalOptions);
return JsonSerializer.Deserialize<T>(json, options);
}
/// <summary>
/// 创建序列化配置
/// </summary>
private static JsonSerializerOptions CreateOptions(JsonSerializerOptions globalOptions)
{
var options = globalOptions != null ? new JsonSerializerOptions(globalOptions) : new JsonSerializerOptions();
options.Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping;
options.Converters.Add(new JsonStringEnumConverter());
options.Converters.Add(new CustomJsonConverter());
return options;
}
}

View File

@ -1,225 +0,0 @@
// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证(版本 2.0)进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动!任何基于本项目二次开发而产生的一切法律纠纷和责任,我们不承担任何责任!
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.Unicode;
namespace Admin.NET.Core;
/// <summary>
/// 自定义JSON属性名称转换器
/// </summary>
public class CustomJsonPropertyConverter : JsonConverter<object>
{
/// <summary>
/// 共享配置选项
/// </summary>
public static readonly JsonSerializerOptions Options = new()
{
Converters = { new CustomJsonPropertyConverter() },
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
PropertyNameCaseInsensitive = true,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
ReferenceHandler = ReferenceHandler.IgnoreCycles,
Encoder = JavaScriptEncoder.Create(UnicodeRanges.All)
};
/// <summary>
/// 缓存类型属性元数据
/// </summary>
private static readonly ConcurrentDictionary<Type, IReadOnlyList<PropertyMeta>> PropertyCache = new();
private readonly string _dateTimeFormat;
public CustomJsonPropertyConverter(string dateTimeFormat = "yyyy-MM-dd HH:mm:ss")
{
_dateTimeFormat = dateTimeFormat;
}
/// <summary>
/// 检查类型是否包含自定义属性
/// </summary>
/// <param name="typeToConvert"></param>
/// <returns></returns>
public override bool CanConvert(Type typeToConvert)
{
return PropertyCache.GetOrAdd(typeToConvert, type =>
type.GetProperties()
.Where(p => p.GetCustomAttribute<CustomJsonPropertyAttribute>() != null)
.Select(p => new PropertyMeta(p))
.ToList().AsReadOnly()
).Count > 0;
}
/// <summary>
/// JSON反序列化
/// </summary>
/// <param name="reader"></param>
/// <param name="typeToConvert"></param>
/// <param name="options"></param>
/// <returns></returns>
public override object Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
var jsonDoc = JsonDocument.ParseValue(ref reader);
var instance = Activator.CreateInstance(typeToConvert);
var properties = PropertyCache.GetOrAdd(typeToConvert, BuildPropertyMeta);
foreach (var prop in properties)
{
if (jsonDoc.RootElement.TryGetProperty(prop.JsonName, out var value))
{
object propertyValue = prop.PropertyType switch
{
Type t when IsDateTimeType(t) => HandleDateTimeValue(value, t),
_ => JsonSerializer.Deserialize(value.GetRawText(), prop.PropertyType, options)
};
prop.SetValue(instance, propertyValue);
}
}
return instance;
}
/// <summary>
/// JSON序列化
/// </summary>
/// <param name="writer"></param>
/// <param name="value"></param>
/// <param name="options"></param>
public override void Write(Utf8JsonWriter writer, object value, JsonSerializerOptions options)
{
writer.WriteStartObject();
var properties = PropertyCache.GetOrAdd(value.GetType(), BuildPropertyMeta);
foreach (var prop in properties)
{
var propertyValue = prop.GetValue(value);
writer.WritePropertyName(prop.JsonName);
if (propertyValue != null && IsDateTimeType(prop.PropertyType))
{
writer.WriteStringValue(FormatDateTime(propertyValue));
}
else
{
JsonSerializer.Serialize(writer, propertyValue, options);
}
}
writer.WriteEndObject();
}
/// <summary>
/// 构建属性元数据缓存
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
private static IReadOnlyList<PropertyMeta> BuildPropertyMeta(Type type)
{
return type.GetProperties()
.Where(p => p.GetCustomAttribute<CustomJsonPropertyAttribute>() != null)
.Select(p => new PropertyMeta(p))
.ToList().AsReadOnly();
}
/// <summary>
/// 处理DateTime类型值
/// </summary>
/// <param name="value"></param>
/// <param name="targetType"></param>
/// <returns></returns>
private object HandleDateTimeValue(JsonElement value, Type targetType)
{
var dateStr = value.GetString();
if (string.IsNullOrEmpty(dateStr)) return null;
var date = DateTime.Parse(dateStr);
return targetType == typeof(DateTimeOffset) ? new DateTimeOffset(date) : date;
}
/// <summary>
/// 格式化DateTime输出
/// </summary>
/// <param name="dateTime"></param>
/// <returns></returns>
private string FormatDateTime(object dateTime)
{
return dateTime switch
{
DateTime dt => dt.ToString(_dateTimeFormat),
DateTimeOffset dto => dto.ToString(_dateTimeFormat),
_ => dateTime?.ToString()
};
}
/// <summary>
/// 检查是否为DateTime类型
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
private static bool IsDateTimeType(Type type)
{
var actualType = Nullable.GetUnderlyingType(type) ?? type;
return actualType == typeof(DateTime) || actualType == typeof(DateTimeOffset);
}
/// <summary>
/// 属性元数据包装类
/// </summary>
private class PropertyMeta
{
private readonly PropertyInfo _property;
private readonly Func<object, object> _getter;
private readonly Action<object, object> _setter;
public string JsonName { get; }
public Type PropertyType => _property.PropertyType;
public PropertyMeta(PropertyInfo property)
{
_property = property;
// 获取自定义属性名或使用原属性名
JsonName = property.GetCustomAttribute<CustomJsonPropertyAttribute>()?.Name ?? property.Name;
// 编译表达式树优化属性访问性能
var instanceParam = Expression.Parameter(typeof(object), "instance");
// Getter表达式编译
var getterExpr = Expression.Lambda<Func<object, object>>(
Expression.Convert(
Expression.Property(
Expression.Convert(instanceParam, property.DeclaringType),
property),
typeof(object)),
instanceParam);
_getter = getterExpr.Compile();
// Setter表达式编译如果属性可写
if (property.CanWrite)
{
var valueParam = Expression.Parameter(typeof(object), "value");
var setterExpr = Expression.Lambda<Action<object, object>>(
Expression.Assign(
Expression.Property(
Expression.Convert(instanceParam, property.DeclaringType),
property),
Expression.Convert(valueParam, property.PropertyType)),
instanceParam, valueParam);
_setter = setterExpr.Compile();
}
}
public object GetValue(object instance) => _getter(instance);
public void SetValue(object instance, object value)
{
_setter?.Invoke(instance, value);
}
}
}

View File

@ -1,25 +0,0 @@
// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证(版本 2.0)进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动!任何基于本项目二次开发而产生的一切法律纠纷和责任,我们不承担任何责任!
using Furion.ConfigurableOptions;
namespace Admin.NET.Plugin.WorkWeixin.Option;
/// <summary>
/// 企业微信配置项
/// </summary>
public class WorkWeixinOptions : IConfigurableOptions
{
/// <summary>
/// 企业ID
/// </summary>
public string CorpId { get; set; }
/// <summary>
/// 企业微信凭证密钥
/// </summary>
public string CorpSecret { get; set; }
}

View File

@ -5,12 +5,11 @@
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动!任何基于本项目二次开发而产生的一切法律纠纷和责任,我们不承担任何责任!
using Admin.NET.Plugin.WorkWeixin.Const;
using Furion.FriendlyException;
using Furion.JsonSerialization;
using Furion.Logging;
using System.Reflection;
using System.Text;
using Admin.NET.Plugin.WorkWeixin.Const;
using Furion.FriendlyException;
using Furion.Logging;
namespace Admin.NET.Plugin.WorkWeixin;
@ -85,7 +84,7 @@ public class WorkWxBaseService(
builder => builder.SetHttpClientName(_options.Value.HttpName).SetRemoteApiAttr(attr)),
HttpMethodEnum.Post => await httpRemoteService.PostAsync(url,
builder => builder.SetHttpClientName(_options.Value.HttpName).SetRemoteApiAttr(attr)
.SetContent(new StringContent(JSON.Serialize(input), Encoding.UTF8, "application/json"))),
.SetContent(new StringContent(CustomJsonHelper.Serialize(input), Encoding.UTF8, "application/json"))),
_ => throw Oops.Oh($"[企业微信] 不支持的请求方式:{attr.HttpMethod.ToString()}({typeof(T).FullName})"),
};
}
@ -112,7 +111,7 @@ public class WorkWxBaseService(
try
{
var resp = JSON.Deserialize<R>(responseContent);
var resp = CustomJsonHelper.Deserialize<R>(responseContent);
if (resp?.ErrCode == 0) return resp;
throw Oops.Oh("[企业微信] 请求失败:" + resp?.ErrMsg);
}