首先依賴注入 懶得下載autofac了 直接用程式集進行批量注入
private static WebApplicationBuilder builder; internal static void Load(WebApplicationBuilder web) { builder = web; builder.Services.Configure<ApiBehaviorOptions>(options => options.SuppressModelStateInvalidFilter = true); Assembly.Load("TestApplication").ExportedTypes.LoadImp(); builder.Services.AddSingleton(typeof(ITestGren<>), typeof(TestGren<>)); } private static void LoadImp(this IEnumerable<Type> type) { type= type.Where(d => d.IsClass&&!d.IsAbstract); foreach (var item in type) { ///檢查是不是泛型類 if (item.GetGenericArguments().Length is 0) item.GetInterfaces().LoadInter(item); } } private static void LoadInter(this Type[] type,Type ImpType) { foreach (var item in type) { if (item.GetGenericArguments().Length is 0) builder.Services.AddSingleton(item,ImpType); } }
可惜泛型類不能直接注入 需要自己寫,反正自己也不怎么寫泛型類
然后我們的介面要驗簽就創建一個類來繼承ValidationAttribute特性
[CheckSgValidation(ErrorMessage ="簽名錯誤")] public class TestModel { public string Sg { get; set; } } public class CsModel:TestModel { public int MyProperty { get; set; } } [AttributeUsage(AttributeTargets.Class )] public class CheckSgValidation: ValidationAttribute { private string SgName = "Sg"; public CheckSgValidation(string sgName) { this.SgName = sgName; } public CheckSgValidation() { } public override bool IsValid(object? value) { StringBuilder sb = new StringBuilder(); foreach (var item in value.GetType().GetProperties()) { if (item.Name == SgName) continue; sb.Append(item.GetValue(value)); } return sb.ToString() == value.GetType().GetProperty(SgName).GetValue(value).ToString(); } }
我是用單獨一個類來寫上我們自定義的特性, 嘗試過用運算式樹進行驗證的 可惜引數為object就不行 不知道怎么處理這個問題
這樣用反射確實可以用

驗證redis登錄驗證碼或其他傳入key,value的特性
internal interface IRedis { bool Get(string key); bool GetDelete(string key); } internal class Redis : IRedis { internal Redis(string conn) { } public bool Get(string key){ return true; } public bool GetDelete(string key){ return false; } } internal static class StaticSingle { public static readonly IRedis _redis; static StaticSingle() { ///本質上單列式一種多型 我們這個靜態建構式式啟動時只運行一次 可以這樣實作單例 _redis = new Redis("127"); } } [AttributeUsage(AttributeTargets.Class|AttributeTargets.Property)] public class CheckRedisValidation : ValidationAttribute { public string key = string.Empty; public string value = https://www.cnblogs.com/bay-max-/p/string.Empty; public bool IsDel=true; public sealed override bool IsValid(object? value) { ///為空說明是放入在屬性上 if(this.key is null) { var array= value.ToString().Split(','); if (array.Length is 1) return false; ///value: "key,value" ///這里自己就不寫讀取比較了 return IsDel ? StaticSingle._redis.GetDelete(array[0]) : StaticSingle._redis.Get(key); } else { key = value.GetType().GetProperty(key).GetValue(value).ToString(); this.value = https://www.cnblogs.com/bay-max-/p/value.GetType().GetProperty(this.value).GetValue(value).ToString().ToLower(); return IsDel ? StaticSingle._redis.GetDelete(key) : StaticSingle._redis.Get(key); } } }
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/514968.html
標籤:.NET Core
