/// <summary> /// 检查接口是否可执行 /// </summary> /// <param name="action"></param> /// <param name="message"></param> /// <returns></returns> public bool Check(IApiAction action, IInlineMessage message) { var user = GlobalContext.User; //1 确定调用方法及对应权限 if (ZeroAppOption.Instance.IsOpenAccess || action.Option.HasFlag(ApiOption.Anymouse)) { return(true); } if (!int.TryParse(user[ZeroTeamJwtClaim.Exp], out int last) || DateTime.Now.ToTimestamp() > last) { FlowTracer.MonitorInfomation(() => $"令牌已过期 => {new DateTime(1970, 1, 1).AddSeconds(last)}"); message.State = MessageState.Deny; message.Result = ApiResultHelper.TokenTimeOutJson; return(false); } //1 确定调用方法及对应权限 if (UserInfo.IsLoginUser(user)) { return(true); } FlowTracer.MonitorInfomation("错误: 需要用户登录信息"); var status = DependencyHelper.GetService <IOperatorStatus>(); status.Code = OperatorStatusCode.BusinessException; status.Message = "拒绝访问"; message.RealState = MessageState.Deny; message.ResultData = status; return(false); }
/// <summary> /// 反序列化(BUG:interface构造) /// </summary> /// <param name="json"></param> /// <returns></returns> public IApiResult <T> DeserializeInterface <T>(string json) { var baseType = typeof(T); if (!interfaceMap.TryGetValue(baseType, out var supType) || supType == null) { var def = DependencyHelper.GetService <T>(); if (def == null) { throw new DependencyException(baseType, $"接口未注册依赖构造"); } else { interfaceMap[baseType] = supType = typeof(ApiResult <>).MakeGenericType(def.GetType()); } } dynamic res = Serializer.ToObject(json, supType); return(new ApiResult <T> { Code = res.Code, Message = res.Message, ResultData = res.ResultData, Trace = res.Trace }); }
public async Task <IApiResult <string> > Hello(string name, int count, Guid guid, byte[] file, long id = -1, Em em = Em.Test) { var test3 = DependencyHelper.GetService <TestObject>(); var test2 = DependencyHelper.GetService <ITest>(nameof(TestObject)); var ctx = context = GlobalContext.Current; await Debug(1, context, context); ScopeRuner.RunScope("Hello2", Hello2); await Debug(1, ctx, GlobalContext.Current); if (DateTime.Now.Ticks % 13 == 11) { Logger.Exception(new Exception("故意的")); } if (DateTime.Now.Ticks % 23 == 19) { Logger.Error("故意的"); } if (DateTime.Now.Ticks % 67 == 57) { Logger.Log(LogLevel.Critical, "故意的"); } return(ApiResultHelper.Helper.Succees($"name:{name} count:{count} guid:{guid} file:{file} id:{id} em:{em}")); }
/// <summary> /// 调用 /// </summary> /// <param name="context"></param> /// <returns></returns> static async Task Call(HttpContext context) { if (string.Equals(context.Request.Method, "OPTIONS", StringComparison.OrdinalIgnoreCase)) { //HttpProtocol.CrosOption(context.Response); return; } if (context.Request.Path == "/") { await context.Response.WriteAsync("Wecome MessageMVC,Lucky every day!", Encoding.UTF8); return; } if (!ZeroAppOption.Instance.IsRuning) { await context.Response.WriteAsync(ApiResultHelper.PauseJson, Encoding.UTF8); return; } //HttpProtocol.CrosCall(context.Response); try { //命令 var reader = new HttpMessageReader(); var(success, message) = await reader.CheckRequest(context); //开始调用 if (success) { var service = ZeroFlowControl.GetService(message.Service) ?? new ZeroService { ServiceName = message.Service, Receiver = new EmptyReceiver(), Serialize = DependencyHelper.GetService <ISerializeProxy>() }; await MessageProcessor.OnMessagePush(service, message, false, new HttpWriter { Context = context }); } else { await context.Response.WriteAsync(ApiResultHelper.NotSupportJson, Encoding.UTF8); } } catch (Exception e) { ScopeRuner.ScopeLogger.Exception(e); try { await context.Response.WriteAsync(ApiResultHelper.BusinessErrorJson, Encoding.UTF8); } catch (Exception exception) { ScopeRuner.ScopeLogger.Exception(exception); } } }
/// <summary> /// 处理 /// </summary> /// <returns></returns> async Task Handle() { Message.RealState = MessageState.Processing; //参数处理 if (!ArgumentPrepare(action)) { return; } Message.ResultSerializer = action.ResultSerializer; Message.ResultCreater = action.ResultCreater; //扩展检查 var checkers = DependencyHelper.GetServices <IApiActionChecker>(); foreach (var checker in checkers) { if (!checker.Check(action, Message)) { return; } } GlobalContext.Current.RequestTask = new ActionTask(); GlobalContext.Current.ActionTask = new TaskCompletionSource <bool>(); try { action.Execute(Message, Service.Serialize); var(state, result) = await GlobalContext.Current.RequestTask.Task; Message.State = state; Message.ResultData = result; } //catch (TaskCanceledException) //{ // Message.State = MessageState.Cancel; // var status = DependencyHelper.GetService<IOperatorStatus>(); // status.Code = OperatorStatusCode.TimeOut; // status.Message = "操作被取消"; // Message.ResultData = status; //} catch (FormatException fe) { FlowTracer.MonitorError(() => $"参数转换出错误, 请检查调用参数是否合适:{fe.Message}"); Message.RealState = MessageState.FormalError; var status = DependencyHelper.GetService <IOperatorStatus>(); status.Code = OperatorStatusCode.ArgumentError; status.Message = "参数转换出错误, 请检查调用参数是否合适"; Message.ResultData = status; } catch (MessageArgumentNullException b) { var msg = $"参数{b.ParamName}不能为空"; FlowTracer.MonitorDetails(msg); Message.RealState = MessageState.FormalError; var status = DependencyHelper.GetService <IOperatorStatus>(); status.Code = OperatorStatusCode.ArgumentError; status.Message = msg; Message.ResultData = status; } }
/// <summary> /// 建造生成器,使用前请调用 /// </summary> public static void CreateBuilder() { if (Builder != null) { return; } Builder = DependencyHelper.GetService <IConfigurationBuilder>() ?? new ConfigurationBuilder(); Builder.SetBasePath(Environment.CurrentDirectory); SyncBuilder(); }
private TRedis CreateClient() { var redis = DependencyHelper.GetService <TRedis>(); redis.Option = Option; if (redis == null) { throw new DependencyException(typeof(TRedis), "未正确注册Redis对象"); } Instances.Add(redis); return(redis); }
/// <summary> /// 发现传输对象 /// </summary> /// <param name="type">控制器类型</param> /// <param name="name">发现的服务名称</param> /// <returns>传输对象构造器</returns> internal static Func <string, IMessageReceiver> DiscoverNetTransport(this Type type, out string name) { foreach (var attr in type.GetCustomAttributes()) { if (attr is IReceiverGet receiverGet) { name = receiverGet.ServiceName; return(receiverGet.Receiver); } } name = ZeroAppOption.Instance.ApiServiceName; return(name => DependencyHelper.GetService <IServiceReceiver>()); }
public ActionResult SetLanguage(string cult, string returnUrl) { var accountService = DependencyHelper.GetService <IMembershipService>(); var unitService = DependencyHelper.GetService <IUnitRepository>(); var language = unitService.GetLanguage(cult); CurrentUser.Identity.LanguageID = language.ID; CurrentUser.Identity.Language = language; accountService.UpdateUserLanguage(CurrentUser.Identity.ID, language.ID); //if (HttpContext.Request.Url != null) //{ // var url = HttpContext.Request.Url.LocalPath; // return RedirectToLocal(url); //} return(RedirectToLocal(returnUrl)); }
IUser ITokenResolver.TokenToUser(string token) { var(success, claims) = CheckJwt(token); if (!success) { return(null); } var user = DependencyHelper.GetService <IUser>(); foreach (var item in claims) { user[item.Type] = item.Value; } return(user); }
public void PrepareSettingPermission() { var settingService = DependencyHelper.GetService <ISettingRepository>(); var settings = settingService.GetSettings(); SettingPermissions = new Dictionary <string, IList <Permission> >(); foreach (string module in settings.Select(m => m.Module).Distinct()) { SettingPermissions.Add(module, new List <Permission>()); foreach (var setting in settings.Where(m => m.Module == module)) { SettingPermissions[module].Add(new Permission { Target = setting.Module, Right = setting.Name, DisplayName = setting.Summary }); } } }
/// <summary> /// 还原参数 /// </summary> public bool RestoreArgument(IInlineMessage message) { ArgumentSerializer ??= DependencyHelper.GetService <ISerializeProxy>(); if (Info.IsDictionaryArgument) { message.RestoryContentToDictionary(ArgumentSerializer, true); } if (message.ArgumentData != null || Option.HasFlag(ApiOption.DictionaryArgument) || Option.HasFlag(ApiOption.CustomContent)) { return(true); } if (ArgumentType != null) { message.ArgumentData = message.GetArgument((int)ArgumentScope, (int)ArgumentSerializeType, ArgumentSerializer, ArgumentType); } return(true); }
/// <summary> /// 参数校验 /// </summary> /// <param name="action"></param> /// <returns></returns> private bool ArgumentPrepare(IApiAction action) { try { action.RestoreArgument(Message); } catch (Exception ex) { var msg = $"错误 : 还原参数异常{ex.Message}"; FlowTracer.MonitorInfomation(msg); var status = DependencyHelper.GetService <IOperatorStatus>(); status.Code = OperatorStatusCode.BusinessException; status.Message = msg; Message.ResultData = status; Message.RealState = MessageState.FormalError; return(false); } try { if (action.ValidateArgument(Message, out var status)) { return(true); } var msg = $"参数校验失败 : {status.Message}"; FlowTracer.MonitorInfomation(msg); Message.ResultData = status; Message.Result = SmartSerializer.ToInnerString(status); Message.RealState = MessageState.FormalError; return(false); } catch (Exception ex) { var msg = $"错误 : 参数校验异常{ex.Message}"; FlowTracer.MonitorInfomation(msg); var status = DependencyHelper.GetService <IOperatorStatus>(); status.Code = OperatorStatusCode.ArgumentError; status.Message = msg; Message.ResultData = status; Message.RealState = MessageState.FormalError; return(false); } }
public void ArgumentInline() { var id = Guid.NewGuid().ToString("N").ToUpper(); IInlineMessage message = new InlineMessage { ID = id, State = MessageState.Accept, Service = "Topic", Method = "Title", Argument = @"{""Value"": ""Content""}", Result = @"{""Value"": ""Result""}" }; message.CheckState(); Assert.IsTrue(message.DataState == (MessageDataState.ArgumentOffline | MessageDataState.ResultOffline), message.DataState.ToString()); //message.PrepareResult(null, ApiResultHelper.State); message.RestoryContent(DependencyHelper.GetService <IJsonSerializeProxy>(), typeof(Argument));; Assert.IsTrue(message.ArgumentData is Argument, message.ArgumentData.GetTypeName()); Assert.IsTrue(message.DataState == (MessageDataState.ArgumentOffline | MessageDataState.ResultOffline | MessageDataState.ArgumentInline), message.DataState.ToString()); }
private static bool CheckToken(IInlineMessage message, IZeroContext context) { if (message.TraceInfo.Token.IsBlank() || !message.IsOutAccess) { return(true); } var resolver = DependencyHelper.GetService <ITokenResolver>(); if (resolver == null) { return(true); } context.User = resolver.TokenToUser(message.TraceInfo.Token); if (context.User[ZeroTeamJwtClaim.Iss] != ToolsOption.Instance.JwtIssue) { FlowTracer.MonitorInfomation(() => $"非法令牌颁发机构 => {context.User[ZeroTeamJwtClaim.Iss]}"); message.State = MessageState.Deny; message.Result = ApiResultHelper.DenyAccessJson; return(false); } return(true); }
void CheckResult() { if (ResultType == null) { ResultSerializeType = SerializeType.None; return; } if (ResultType == typeof(void)) { IsAsync = false; ResultType = null; ResultSerializeType = SerializeType.None; return; } if (ResultType == typeof(Task)) { IsAsync = true; ResultType = null; ResultSerializeType = SerializeType.None; return; } if (ResultType.IsGenericType && ResultType.IsSubclassOf(typeof(Task))) { IsAsync = true; ResultType = ResultType.GetGenericArguments()[0]; } else { IsAsync = false; } if (ResultType.IsValueType) { //var def = ResultType.InvokeMember(null, BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.CreateInstance, null, null, null); ResultCreater = (code, msg) => msg; ResultSerializer = new SerializeProxy(); ResultSerializeType = SerializeType.Custom; } else if (ResultType == typeof(string)) { ResultCreater = (code, msg) => msg; ResultSerializer = new SerializeProxy(); ResultSerializeType = SerializeType.Custom; } else { if (ResultType.IsSupperInterface(typeof(IOperatorStatus))) { ResultCreater = (code, msg) => { var re = DependencyHelper.GetService <IOperatorStatus>(); re.Code = code; re.Message = msg; return(re); } } ; switch (ResultSerializeType) { case SerializeType.Json: ResultSerializer = DependencyHelper.GetService <IJsonSerializeProxy>(); break; case SerializeType.NewtonJson: ResultSerializer = new NewtonJsonSerializeProxy(); break; case SerializeType.Xml: ResultSerializer = new XmlSerializeProxy(); break; case SerializeType.Custom: ResultSerializer = new SerializeProxy(); break; case SerializeType.Bson: throw new NotSupportedException($"{ResultSerializeType}序列化方式暂不支持"); } } }
public void MessageLifeCycle() { var id = Guid.NewGuid().ToString("N").ToUpper(); IInlineMessage message = new InlineMessage { ID = id, State = MessageState.Accept, Service = "Topic", Method = "Title", Argument = @"{""Value"": ""Content""}", Result = @"{""Value"": ""Result""}" }; message.CheckState(); Assert.IsTrue(message.DataState == (MessageDataState.ArgumentOffline | MessageDataState.ResultOffline), message.DataState.ToString()); //message.PrepareResult(null, ApiResultHelper.State); message.RestoryContent(DependencyHelper.GetService <IJsonSerializeProxy>(), typeof(Argument));; Assert.IsTrue(message.ArgumentData is Argument, message.ArgumentData.GetTypeName()); Assert.IsTrue(message.DataState == (MessageDataState.ArgumentOffline | MessageDataState.ResultOffline | MessageDataState.ArgumentInline), message.DataState.ToString()); message = new InlineMessage { ID = id, State = MessageState.Accept, Service = "Topic", Method = "Title", Argument = @"{""Value"": ""Content""}", Result = @"{""Value"": ""Result""}" }; message.ResetToRequest(); Assert.IsTrue(message.DataState == MessageDataState.ArgumentOffline, message.DataState.ToString()); Assert.IsTrue(message.Result == null, message.Result); //message.PrepareResult(null, ApiResultHelper.State); message.RestoryContent(DependencyHelper.GetService <IJsonSerializeProxy>(), typeof(Argument));; Assert.IsTrue(message.DataState == (MessageDataState.ArgumentOffline | MessageDataState.ArgumentInline), message.DataState.ToString()); message.ResultData = new Argument <int> { Value = 1 }; Assert.IsTrue(message.DataState == (MessageDataState.ArgumentOffline | MessageDataState.ArgumentInline | MessageDataState.ResultInline), message.DataState.ToString()); message.OfflineResult(); Assert.IsTrue(message.Result != null, message.Result); Assert.IsTrue(message.DataState == (MessageDataState.ArgumentOffline | MessageDataState.ArgumentInline | MessageDataState.ResultOffline | MessageDataState.ResultInline), message.DataState.ToString()); var result = message.ToMessageResult(true); var json = SmartSerializer.ToString(result); var result2 = SmartSerializer.ToObject <MessageResult>(json); Assert.IsTrue(result2.ID == message.ID, result2.ID); Assert.IsTrue(result2.ResultData == result.ResultData, result2.ResultData.GetTypeName()); Assert.IsTrue(result2.State == result.State, result2.State.ToString()); Assert.IsTrue(result2.DataState == result.DataState, result2.DataState.ToString()); Assert.IsTrue(result2.Result == result.Result, result2.Result); Assert.IsTrue(result2.Trace.LocalMachine == message.TraceInfo.LocalMachine, result2.Trace.LocalMachine); }
IMessageReceiver IReceiverGet.Receiver(string service) { return(DependencyHelper.GetService <INetEvent>()); }
public static void SetDefaultCurrency() { var repo = DependencyHelper.GetService <IUnitRepository>(); _baseCurrency = repo.GetDefaultCurrency(); }
private void RegistToZero() { foreach (var serviceInfo in ServiceInfos.Values) { if (serviceInfo.Aips.Count == 0) { continue; } logger.Debug(() => $"【注册API】 {serviceInfo.Name}"); var service = ZeroFlowControl.TryGetZeroObject(serviceInfo.Name); if (service == null) { var receiver = serviceInfo.NetBuilder(serviceInfo.Name); if (receiver == null || receiver is EmptyService) { service = new EmptyService { IsAutoService = true, ServiceName = serviceInfo.Name, Serialize = serviceInfo.Serialize switch { SerializeType.Json => DependencyHelper.GetService <IJsonSerializeProxy>(), SerializeType.NewtonJson => new NewtonJsonSerializeProxy(), SerializeType.Xml => DependencyHelper.GetService <IXmlSerializeProxy>(), SerializeType.Bson => DependencyHelper.GetService <IBsonSerializeProxy>(), _ => DependencyHelper.GetService <IJsonSerializeProxy>(), } } } ; else { service = new ZeroService { IsAutoService = true, ServiceName = serviceInfo.Name, Receiver = receiver, Serialize = serviceInfo.Serialize switch { SerializeType.Json => DependencyHelper.GetService <IJsonSerializeProxy>(), SerializeType.NewtonJson => new NewtonJsonSerializeProxy(), SerializeType.Xml => DependencyHelper.GetService <IXmlSerializeProxy>(), SerializeType.Bson => DependencyHelper.GetService <IBsonSerializeProxy>(), _ => DependencyHelper.GetService <IJsonSerializeProxy>(), } } }; ZeroFlowControl.RegistService(ref service); } foreach (var api in serviceInfo.Aips) { try { var info = (ApiActionInfo)api.Value; if (api.Key == "*") { logger.Debug(() => $"[注册接口] {serviceInfo.Name}/* => {info.Caption} {info.ControllerName}.{info.Name}"); service.RegistWildcardAction(info); } else if (!service.RegistAction(api.Key, info)) { logger.Error($"[注册接口]失败,因为路由名称已存在 {serviceInfo.Name}/{api.Key} => {info.Caption} {info.ControllerName}.{info.Name}"); } else { logger.Debug(() => $"[注册接口] {serviceInfo.Name}/{api.Key} => {info.Caption} {info.ControllerName}.{info.Name}"); } } catch (Exception ex) { logger.Exception(ex, api.Key); } } }
IMessageReceiver IReceiverGet.Receiver(string service) { return(ReceiverName == null ? null : DependencyHelper.GetService <IMessageReceiver>(ReceiverName)); }
public string Json(Argument argument) { return(DependencyHelper.GetService <IJsonSerializeProxy>().ToString(argument)); }
/// <summary> /// 构造 /// </summary> public ZeroContextEx() { User = DependencyHelper.GetService <IUser>();//防止反序列化失败 }
public void Prepare() { var unitRepository = DependencyHelper.GetService <IUnitRepository>(); Languages = unitRepository.GetAllLanguages(); ResourceModels = new List <ResourceModel>(); var languageResourceModels = new List <LanguageResourceModel>(); foreach (var language in Languages) { var path1 = ""; var path2 = ""; if (language.Value.ToLower().Contains("en")) { path1 = HttpContext.Current.Server.MapPath("~/App_GlobalResources/Resource.resx"); path2 = HttpContext.Current.Server.MapPath("~/App_GlobalResources/MenuResource.resx"); } else { path1 = HttpContext.Current.Server.MapPath("~/App_GlobalResources/Resource." + language.Value + ".resx"); path2 = HttpContext.Current.Server.MapPath("~/App_GlobalResources/MenuResource." + language.Value + ".resx"); } var res = new LanguageResourceModel(path1, path2, language.Value); languageResourceModels.Add(res); } var languageResourceModel = languageResourceModels.FirstOrDefault(m => m.LanguageCode.ToLower().Contains("en")); if (languageResourceModel != null) { foreach (XmlNode nodeRoot in languageResourceModel.Resources) { var resourceModel = new ResourceModel(); resourceModel.Code = nodeRoot.Attributes.Item(0).Value; try { //add for english default resourceModel.Resources.Add(new ResourceItemModel { Code = nodeRoot.Attributes.Item(0).Value, Description = nodeRoot.ChildNodes.Item(1).FirstChild.Value, LanguageCode = "en" }); } catch (Exception) { //add for english default resourceModel.Resources.Add(new ResourceItemModel { Code = nodeRoot.Attributes.Item(0).Value, Description = nodeRoot.ChildNodes.Item(1).FirstChild.Value, LanguageCode = "en" }); throw; } // foreach (var model in languageResourceModels.Where(m => !m.LanguageCode.ToLower().Contains("en"))) { var node = model.Resources.FirstOrDefault(m => m.Attributes.Item(0).Value == nodeRoot.Attributes.Item(0).Value); if (node != null) { resourceModel.Resources.Add(new ResourceItemModel { Code = nodeRoot.Attributes.Item(0).Value, Description = node.ChildNodes.Item(1).FirstChild.Value, LanguageCode = model.LanguageCode }); } else { resourceModel.Resources.Add(new ResourceItemModel { Code = nodeRoot.Attributes.Item(0).Value, Description = nodeRoot.ChildNodes.Item(1).FirstChild.Value, LanguageCode = model.LanguageCode }); } } ResourceModels.Add(resourceModel); } } }
IMessageReceiver IReceiverGet.Receiver(string service) { return(DependencyHelper.GetService <IMessageConsumer>()); }
public void PrepareLanguages() { var unitRepository = DependencyHelper.GetService <IUnitRepository>(); Languages = unitRepository.GetAllLanguages(); }