/// <summary> /// 从Json配置文件中初始化显示 /// </summary> /// <param name="jsonData">JSON数据</param> public static void InitFromJsonData(string jsonData) { if (string.IsNullOrWhiteSpace(jsonData)) { return; } DisplayCollection displayCollection = JsonSerialize.JsonToObject <DisplayCollection>(jsonData); if (displayCollection == null || displayCollection.Types == null) { return; } foreach (var type in displayCollection.Types) { if (type == null || string.IsNullOrWhiteSpace(type.TypeFullName) || type.Propertys == null) { continue; } Type modelType = Type.GetType(type.TypeFullName); if (modelType == null) { continue; } foreach (var propertyDisplay in type.Propertys) { if (propertyDisplay == null || string.IsNullOrWhiteSpace(propertyDisplay.Name) || propertyDisplay.Display == null) { continue; } DisplayManager.Add(modelType, propertyDisplay.Name, propertyDisplay.Display.DisplayName); } } }
/// <summary> /// execute api /// </summary> /// <typeparam name="T">return data type</typeparam> /// <param name="apiObjectName">api object name </param> /// <param name="endpointName">endpoint</param> /// <param name="request">request</param> /// <returns></returns> public static async Task <T> PostAsync <T>(string apiObjectName, string endpointName, ApiRequest request) { var apiObject = GetApiObject(apiObjectName); if (apiObject == null) { throw new Exception(string.Format("didn't config api {0}", apiObjectName)); } var apiServer = apiObject.GetServer(); if (apiServer == null) { throw new Exception(string.Format("set up at least one server info for api {0}", apiObjectName)); } var endpoint = GetApiEndpoint(apiObjectName, endpointName); if (endpoint == null) { throw new Exception(string.Format("didn't set endpoint for {0}", endpointName)); } var response = await HttpUtil.HttpPostJsonAsync(apiServer.GetEndpointPath(endpoint.Path), request).ConfigureAwait(false); string stringValue = await response.Content.ReadAsStringAsync().ConfigureAwait(false); return(JsonSerialize.JsonToObject <T>(stringValue)); }
/// <summary> /// 根据登陆账号身份编号获取session /// </summary> /// <param name="subject">身份编号</param> /// <returns></returns> public static async Task <AuthSession> GetSessionBySubjectAsync(string subject) { if (subject == null) { return(null); } var sessionResponse = await CacheManager.StringGetAsync(new StringGetRequest() { CacheObject = GetCacheObject(), Keys = new List <string>() { subject } }).ConfigureAwait(false); if (!(sessionResponse?.Success ?? false) || sessionResponse.Values.IsNullOrEmpty()) { return(null); } var sessionValue = sessionResponse.Values.First()?.Value.ToString() ?? string.Empty; var session = JsonSerialize.JsonToObject <AuthSession>(sessionValue); if (!(session?.AllowUse() ?? false)) { session = null; } return(session); }
/// <summary> /// Authorize Verify /// </summary> /// <param name="verifyRequest">verify request</param> /// <returns></returns> public static async Task <AuthorizeVerifyResult> AuthorizeVerifyAsync(AuthorizeVerifyRequest verifyRequest) { if (verifyRequest == null) { return(AuthorizeVerifyResult.ForbidResult()); } if (!authorizeConfig.RemoteAuthorizeVerify) { if (AuthorizeVerifyProcessAsync == null) { throw new ArgumentNullException(nameof(AuthorizeVerifyProcessAsync)); } return((await AuthorizeVerifyProcessAsync(verifyRequest).ConfigureAwait(false)) ?? AuthorizeVerifyResult.ForbidResult()); } string server = authorizeConfig.GetRandomServer(); if (server.IsNullOrEmpty()) { throw new ArgumentNullException(nameof(authorizeConfig.Servers)); } var result = await HttpUtil.HttpPostJsonAsync(server, verifyRequest).ConfigureAwait(false); var stringValue = await result.Content.ReadAsStringAsync().ConfigureAwait(false); AuthorizeVerifyResult verifyResult = JsonSerialize.JsonToObject <AuthorizeVerifyResult>(stringValue); return(verifyResult ?? AuthorizeVerifyResult.ForbidResult()); }
/// <summary> /// upload file /// </summary> /// <param name="url">url</param> /// <param name="files">files</param> /// <param name="parameters">parameters</param> /// <returns>upload result</returns> public static UploadResult Upload(string url, Dictionary <string, byte[]> files, Dictionary <string, string> parameters = null) { #region verify args if (url.IsNullOrEmpty()) { return(new UploadResult() { Success = false, ErrorMsg = "url is null or empty" }); } if (files == null || files.Count <= 0) { return(new UploadResult() { Success = false, ErrorMsg = "not set any files to upload" }); } #endregion string responseVal = HttpCall(url, parameters, files); return(JsonSerialize.JsonToObject <UploadResult>(responseVal)); }
/// <summary> /// object deep clone /// </summary> /// <typeparam name="T">data type</typeparam> /// <param name="sourceObj">object</param> /// <returns>new object</returns> public static T DeepClone <T>(this T sourceObj) { if (sourceObj == null) { return(default(T)); } var objectString = JsonSerialize.ObjectToJson <T>(sourceObj); return(JsonSerialize.JsonToObject <T>(objectString)); }
/// <summary> /// 验证登陆凭据 /// </summary> /// <param name="principal">登陆凭据</param> /// <returns></returns> public static async Task <bool> VerifyCredentialAsync(ClaimsPrincipal principal, AuthenticationProperties properties) { IConfiguration configuration = HttpContextHelper.Current.RequestServices.GetService(typeof(IConfiguration)) as IConfiguration; if (configuration == null) { throw new Exception("get IConfiguration fail"); } var unityClientOptions = HttpContextHelper.Current.RequestServices.GetService <IOptionsMonitor <UnityAuthenticationClientOption> >().Get(Constants.UnityAuthenticationScheme); if (unityClientOptions == null) { throw new Exception("get UnityAuthenticationClientOption fail"); } var openIdOption = HttpContextHelper.Current.RequestServices.GetService <IOptionsMonitor <OpenIdConnectOptions> >().Get(OpenIdConnectDefaults.AuthenticationScheme); if (openIdOption == null) { throw new Exception("get OpenIdConnectOptions fail"); } UnityAuthenticationCredentialVerifyRequest request = new UnityAuthenticationCredentialVerifyRequest() { Client = new IdentityServer4.Models.Client() { ClientId = openIdOption.ClientId, ClientSecrets = new List <Secret>() { new Secret(openIdOption.ClientSecret.Sha256()) } }, Claims = principal.Claims.ToDictionary(c => c.Type, c => c.Value) }; string url = unityClientOptions.CredentialVerifyUrl; if (string.IsNullOrWhiteSpace(url)) { url = openIdOption.Authority + "/" + Constants.RoutePaths.CredentialVerify; } try { var result = await HttpUtil.HttpPostJsonAsync(url, request).ConfigureAwait(false); var stringValue = await result.Content.ReadAsStringAsync().ConfigureAwait(false); UnityAuthenticationCredentialVerifyResult verifyResult = JsonSerialize.JsonToObject <UnityAuthenticationCredentialVerifyResult>(stringValue); var loginSuccess = verifyResult?.VerifySuccess ?? false; return(loginSuccess); } catch (Exception ex) { throw ex; } }
/// <summary> /// config data through json /// </summary> /// <param name="dataConfigJson">json value</param> public static void Config(string dataConfigJson) { if (string.IsNullOrWhiteSpace(dataConfigJson)) { return; } var dataConfig = JsonSerialize.JsonToObject <DataConfig>(dataConfigJson); if (dataConfig == null) { return; } Config(dataConfig); }
static T DeepCloneByJson <T>(T sourceObj) { if (sourceObj == null) { return(default(T)); } var objectString = JsonSerialize.ObjectToJson(sourceObj, false); return(JsonSerialize.JsonToObject <T>(objectString, new JsonSerializeSetting() { ResolveNonPublic = false, DeserializeType = sourceObj.GetType() })); }
/// <summary> /// upload file /// </summary> /// <param name="url">url</param> /// <param name="files">files</param> /// <param name="parameters">parameters</param> /// <returns>upload result</returns> public static async Task <UploadResult> UploadAsync(string url, Dictionary <string, byte[]> files, Dictionary <string, string> parameters = null) { #region verify args if (url.IsNullOrEmpty()) { return(new UploadResult() { Success = false, ErrorMessage = "url is null or empty" }); } if (files == null || files.Count <= 0) { return(new UploadResult() { Success = false, ErrorMessage = "not set any files to upload" }); } #endregion string responseVal = await HttpResponseStringAsync(new HttpRequestOption() { RequestFiles = files, RequestMessage = new HttpRequestMessage() { Method = HttpMethod.Post, RequestUri = new Uri(url) }, RequestParameters = parameters, UseCookie = true }).ConfigureAwait(false); var result = JsonSerialize.JsonToObject <UploadResult>(responseVal); result?.Files?.ForEach(f => { f.Target = UploadTarget.Remote; }); return(result); }
UnityAuthenticationCredentialVerifyRequest BuildCredentialVerifyRequest(HttpContext context) { string requestValue = string.Empty; StreamReader reader = new StreamReader(context.Request.Body); requestValue = reader.ReadToEnd(); if (string.IsNullOrWhiteSpace(requestValue)) { return(null); } try { var request = JsonSerialize.JsonToObject <UnityAuthenticationCredentialVerifyRequest>(requestValue); return(request); } catch (Exception ex) { Logger.LogError(ex.Message); return(null); } }
/// <summary> /// upload by request /// </summary> /// <param name="request">http request</param> /// <returns></returns> public static async Task <UploadResult> UploadByRequestAsync(HttpRequest request) { if (request == null) { return(UploadResult.Empty); } var uploadParameter = JsonSerialize.JsonToObject <RemoteUploadParameter>(request.Form[RemoteUploadParameter.REQUEST_KEY]); if (uploadParameter == null) { return(UploadResult.Empty); } Dictionary <string, byte[]> files = new Dictionary <string, byte[]>(); if (!request.Form.Files.IsNullOrEmpty()) { foreach (var file in request.Form.Files) { files.Add(file.FileName, file.OpenReadStream().ToBytes()); } } return(await UploadByConfigAsync(uploadParameter.Files, files, HttpRequestHelper.GetHttpContextParameters(request)).ConfigureAwait(false)); }
/// <summary> /// 验证登陆凭据 /// </summary> /// <param name="principal">登陆凭据</param> /// <returns></returns> public static async Task <bool> VerifyCredentialAsync(ClaimsPrincipal principal, AuthenticationProperties properties) { IConfiguration configuration = HttpContextHelper.Current.RequestServices.GetService(typeof(IConfiguration)) as IConfiguration; if (configuration == null) { throw new Exception("get IConfiguration fail"); } var ssoOptions = HttpContextHelper.Current.RequestServices.GetService <IOptionsMonitor <SSOAuthenticationOption> >().Get(Constants.SSOAuthenticationScheme); //configuration.Get<SSOAuthenticationOption>();//(HttpContextHelper.Current.RequestServices.GetService(typeof(IOptions<SSOAuthenticationOption>)) as IOptions<SSOAuthenticationOption>)?.Value; if (ssoOptions == null) { throw new Exception("get SSOAuthenticationOption fail"); } var openIdOption = HttpContextHelper.Current.RequestServices.GetService <IOptionsMonitor <OpenIdConnectOptions> >().Get(OpenIdConnectDefaults.AuthenticationScheme); if (openIdOption == null) { throw new Exception("get OpenIdConnectOptins fail"); } var subjectClaim = principal.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier); if (subjectClaim == null) { subjectClaim = principal.Claims.FirstOrDefault(c => c.Type == JwtClaimTypes.Subject); } if (subjectClaim == null || string.IsNullOrWhiteSpace(subjectClaim.Value)) { //await HttpContextHelper.Current.SignOutAsync(); return(false); } CredentialVerifyRequest request = new CredentialVerifyRequest() { Client = new IdentityServer4.Models.Client() { ClientId = openIdOption.ClientId, ClientSecrets = new List <Secret>() { new Secret(openIdOption.ClientSecret.Sha256()) } }, User = new CredentialUser() { Id = subjectClaim.Value } }; string url = ssoOptions.CredentialVerifyUrl; if (string.IsNullOrWhiteSpace(url)) { url = openIdOption.Authority + "/" + Constants.RoutePaths.CredentialVerify; } try { HttpClient client = new HttpClient(); var result = await client.PostAsJsonAsync(url, request).ConfigureAwait(false); var stringValue = await result.Content.ReadAsStringAsync().ConfigureAwait(false); CredentialVerifyResult verifyResult = JsonSerialize.JsonToObject <CredentialVerifyResult>(stringValue); var loginSuccess = verifyResult?.VerifySuccess ?? false; //if (!loginSuccess) //{ // await HttpContextHelper.Current.SignOutAsync(); //} return(loginSuccess); } catch (Exception ex) { //await HttpContextHelper.Current.SignOutAsync(); throw ex; } }
/// <summary> /// 通过JSON格式配置内容初始化验证 /// </summary> /// <param name="json"></param> public static void InitFromJson(string json) { if (string.IsNullOrWhiteSpace(json)) { return; } RuleCollection ruleCollection = JsonSerialize.JsonToObject <RuleCollection>(json); if (ruleCollection == null || ruleCollection.Rules == null) { return; } foreach (var typeRule in ruleCollection.Rules) { if (typeRule == null || string.IsNullOrWhiteSpace(typeRule.TypeFullName) || typeRule.Rules == null) { continue; } Type modelType = Type.GetType(typeRule.TypeFullName); if (modelType == null) { continue; } //加载类型属性和字段 List <MemberInfo> memberInfoList = new List <MemberInfo>(); memberInfoList.AddRange(modelType.GetFields(BindingFlags.Public | BindingFlags.Instance)); memberInfoList.AddRange(modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance)); ParameterExpression parExp = Expression.Parameter(modelType);//参数表达式 Array parameterArray = Array.CreateInstance(typeof(ParameterExpression), 1); parameterArray.SetValue(parExp, 0); Type valFieldType = typeof(ValidationField <>).MakeGenericType(modelType); foreach (var propertyRule in typeRule.Rules) { if (propertyRule == null || propertyRule.Rules == null) { return; } string[] propertyNameArray = propertyRule.Name.LSplit("."); Expression propertyExpress = null; foreach (string pname in propertyNameArray) { if (propertyExpress == null) { propertyExpress = Expression.PropertyOrField(parExp, pname); } else { propertyExpress = Expression.PropertyOrField(propertyExpress, pname); } } Type funcType = typeof(Func <,>).MakeGenericType(modelType, typeof(object));//委托函数类型 var genericLambdaMethod = lambdaMethod.MakeGenericMethod(funcType); var lambdaExpression = genericLambdaMethod.Invoke(null, new object[] { Expression.Convert(propertyExpress, typeof(object)), parameterArray }); if (lambdaExpression == null) { continue; } foreach (var rule in propertyRule.Rules) { var fieldInstance = Activator.CreateInstance(valFieldType); valFieldType.GetProperty("FieldExpression").SetValue(fieldInstance, lambdaExpression); valFieldType.GetProperty("ErrorMessage").SetValue(fieldInstance, rule.ErrorMessage); valFieldType.GetProperty("TipMessage").SetValue(fieldInstance, rule.TipMessage); Array valFieldArray = Array.CreateInstance(valFieldType, 1); valFieldArray.SetValue(fieldInstance, 0); switch (rule.ValidateType) { case ValidatorType.Email: MethodInfo emailMethod = validationMethods.FirstOrDefault(c => c.Name == "Email"); if (emailMethod == null) { continue; } emailMethod.MakeGenericMethod(modelType).Invoke(null, new object[] { valFieldArray }); break; case ValidatorType.CreditCard: MethodInfo creditMethod = validationMethods.FirstOrDefault(c => c.Name == "CreditCard"); if (creditMethod == null) { continue; } creditMethod.MakeGenericMethod(modelType).Invoke(null, new object[] { valFieldArray }); break; case ValidatorType.EnumType: MethodInfo enumMethod = validationMethods.FirstOrDefault(c => c.Name == "EnumType"); if (enumMethod == null) { continue; } Type enumType = Type.GetType(rule.EnumType); if (enumType == null) { continue; } enumMethod.MakeGenericMethod(modelType).Invoke(null, new object[] { enumType, valFieldArray }); break; case ValidatorType.MaxLength: MethodInfo maxLengthMethod = validationMethods.FirstOrDefault(c => c.Name == "MaxLength"); if (maxLengthMethod == null) { continue; } maxLengthMethod.MakeGenericMethod(modelType).Invoke(null, new object[] { Convert.ToInt32(rule.MaxValue), valFieldArray }); break; case ValidatorType.MinLength: MethodInfo minLengthMethod = validationMethods.FirstOrDefault(c => c.Name == "MinLength"); if (minLengthMethod == null) { continue; } minLengthMethod.MakeGenericMethod(modelType).Invoke(null, new object[] { Convert.ToInt32(rule.MinValue), valFieldArray }); break; case ValidatorType.Phone: MethodInfo phoneMethod = validationMethods.FirstOrDefault(c => c.Name == "Phone"); if (phoneMethod == null) { continue; } phoneMethod.MakeGenericMethod(modelType).Invoke(null, new object[] { valFieldArray }); break; case ValidatorType.Range: MethodInfo rangeMethod = validationMethods.FirstOrDefault(c => c.Name == "Range"); if (rangeMethod == null) { continue; } rangeMethod.MakeGenericMethod(modelType).Invoke(null, new object[] { rule.MinValue, rule.MaxValue, rule.LowerBoundary, rule.UpperBoundary, valFieldArray }); break; case ValidatorType.RegularExpression: MethodInfo regularExpressionMethod = validationMethods.FirstOrDefault(c => c.Name == "RegularExpression"); if (regularExpressionMethod == null) { continue; } regularExpressionMethod.MakeGenericMethod(modelType).Invoke(null, new object[] { rule.Value, valFieldArray }); break; case ValidatorType.Required: MethodInfo requiredMethod = validationMethods.FirstOrDefault(c => c.Name == "Required"); if (requiredMethod == null) { continue; } requiredMethod.MakeGenericMethod(modelType).Invoke(null, new object[] { valFieldArray }); break; case ValidatorType.Url: MethodInfo urlMethod = validationMethods.FirstOrDefault(c => c.Name == "Url"); if (urlMethod == null) { continue; } urlMethod.MakeGenericMethod(modelType).Invoke(null, new object[] { valFieldArray }); break; case ValidatorType.StringLength: MethodInfo strLengthMethod = validationMethods.FirstOrDefault(c => c.Name == "StringLength"); if (strLengthMethod == null) { continue; } strLengthMethod.MakeGenericMethod(modelType).Invoke(null, new object[] { Convert.ToInt32(rule.MaxValue), Convert.ToInt32(rule.MinValue), valFieldArray }); break; case ValidatorType.Compare: MethodInfo compareMethod = validationMethods.FirstOrDefault(c => c.Name == "SetCompareValidation"); if (compareMethod == null) { continue; } object compareValue = rule.Value; switch (rule.CompareTarget) { case CompareObject.Field: string[] comparePropertyNameArray = compareValue.ToString().LSplit("."); Expression comparePropertyExpress = null; foreach (string pname in comparePropertyNameArray) { if (comparePropertyExpress == null) { comparePropertyExpress = Expression.PropertyOrField(parExp, pname); } else { comparePropertyExpress = Expression.PropertyOrField(comparePropertyExpress, pname); } } var compareLambdaExpression = lambdaMethod.MakeGenericMethod(funcType).Invoke(null, new object[] { Expression.Convert(comparePropertyExpress, typeof(object)), parameterArray }); if (compareLambdaExpression == null) { continue; } compareValue = compareLambdaExpression; break; default: if (rule.Operator == CompareOperator.In || rule.Operator == CompareOperator.NotIn) { IEnumerable <dynamic> valueArray = compareValue.ToString().LSplit(","); compareValue = valueArray; } break; } compareMethod.MakeGenericMethod(modelType).Invoke(null, new object[] { rule.Operator, compareValue, fieldInstance }); break; } } } } }