示例#1
0
 public override Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
 {
     try
     {
         IHttpContextAccessor  httpContextAccessor  = AspectCoreContainer.CreateScope().Resolve <IHttpContextAccessor>();
         IMonitorLogRepository monitorLogRepository = AspectCoreContainer.CreateScope().Resolve <IMonitorLogRepository>();
         DateTime   time      = (DateTime)context.HttpContext.Items[key];
         var        request   = context.HttpContext.Request;
         var        headerStr = JsonConvert.SerializeObject(request.Headers);
         MonitorLog monLog    = new MonitorLog()
         {
             ExecuteStartTime = time,
             ExecuteEndTime   = DateTime.UtcNow,
             IP                 = httpContextAccessor.HttpContext.GetRequestIp4Address()?.ToString(),
             ClientAgent        = ((HttpRequestHeaders)((DefaultHttpRequest)request).Headers).HeaderUserAgent,
             Path               = (request.Path.HasValue ? request.Path.ToString() : "") + (request.QueryString.HasValue ? request.QueryString.ToString() : ""),
             ActionParams       = StreamHelper.GetStreamText(request.Body),
             HttpRequestHeaders = headerStr,
             HttpMethod         = request.Method,
             Response           = JsonConvert.SerializeObject(context.Result)
         };
         monLog.Elapsed = monLog.CostTime;
         monitorLogRepository.Insert(monLog);
         //Log4NetHelper.WriteDebug(GetType(), monLog.ToString());
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
     }
     return(base.OnResultExecutionAsync(context, next));
 }
示例#2
0
        public async Task <ExcutedResult> SendAsync(string phoneNumber, string content, int client, String countryNumber = "", string templateCode = "")
        {
            var result = await Send(phoneNumber, content, client, countryNumber, templateCode);

            IHttpContextAccessor httpContextAccessor = AspectCoreContainer.Resolve <IHttpContextAccessor>();
            var clientIp = httpContextAccessor.HttpContext.GetRequestIp4Address().ToString();

            var smsSend = new SmsSend
            {
                Id           = Guid.NewGuid(),
                Mobile       = result.PhoneNumber,
                Content      = result.Content,
                CreateTime   = DateTime.UtcNow,
                SmsProxy     = Name,
                SmsProxyResp = result.ResponseStr,
                IsSuccess    = result.IsSuccess,
                Client       = client,
                LoginIp      = clientIp
            };

            ISmsSendRepository smsSendRepository = AspectCoreContainer.Resolve <ISmsSendRepository>();

            smsSendRepository.Insert(smsSend);

            if (result.IsSuccess)
            {
                return(ExcutedResult.SuccessResult());
            }

            return(ExcutedResult.FailedResult(BusinessResultCode.SmsSendFail, "短信发送失败"));
        }
        public void TestGenerateEntitiesForPostgreSql()
        {
            BuildServiceForPostgreSql();
            var dbContext = AspectCoreContainer.Resolve <IDbContextCore>();

            dbContext.GenerateAllCodesFromDatabase(true);
        }
        /// <summary>
        /// 根据数据表生成Model层、Controller层、IRepository层和Repository层代码
        /// </summary>
        /// <param name="ifExsitedCovered">是否覆盖已存在的同名文件</param>
        public static void GenerateAllCodesFromDatabase(bool ifExsitedCovered = false)
        {
            var dbContext = AspectCoreContainer.Resolve <IDbContextCore>();

            if (dbContext == null)
            {
                throw new Exception("未能获取到数据库上下文,请先注册数据库上下文。");
            }
            var tables = dbContext.GetCurrentDatabaseTableList();

            if (tables != null && tables.Any())
            {
                foreach (var table in tables)
                {
                    if (table.Columns.Any(c => c.IsPrimaryKey))
                    {
                        var pkTypeName = table.Columns.First(m => m.IsPrimaryKey).CSharpType;
                        GenerateEntity(table, ifExsitedCovered);
                        GenerateIRepository(table.TableName.ToPascalCase(), pkTypeName, ifExsitedCovered);
                        GenerateRepository(table.TableName.ToPascalCase(), pkTypeName, ifExsitedCovered);
                        GenerateController(table.TableName.ToPascalCase(), pkTypeName, ifExsitedCovered);
                    }
                }
            }
        }
示例#5
0
 /// <summary>
 /// IoC初始化
 /// </summary>
 /// <param name="services"></param>
 /// <returns></returns>
 private IServiceProvider InitIoC(IServiceCollection services)
 {
     //services.UseOracle(Configuration);
     //services.UseMysql(Configuration);
     //services.UseSqlServer(Configuration);
     return(AspectCoreContainer.BuildServiceProvider(services));//接入AspectCore.Injector
 }
示例#6
0
        /// <summary>
        /// 发送验证码
        /// </summary>
        /// <param name="phoneNumber">手机号</param>
        /// <param name="countryCode">国际电话区号,发送国际短信为必传字段</param>
        /// <returns>执行结果</returns>
        public async Task <ExcutedResult <string> > SendCaptcha(string phoneNumber, string countryCode)
        {
            try
            {
                var oldCaptcha = Repository.CheckMobileCaptcha(phoneNumber);
                if (oldCaptcha != null)
                {
                    return(ExcutedResult <string> .SuccessResult("", oldCaptcha.Id.ToString()));
                }
                IConfiguration config        = AspectCoreContainer.Resolve <IConfiguration>();
                var            expireSeconds = int.Parse(config["Captcha:Common:ExpireSeconds"]);
                var            captcha       = CodeHelper.CreateMobileCode(phoneNumber);

                var entity = new DataAccess.Entities.Captcha
                {
                    Id          = Guid.NewGuid(),
                    Code        = captcha,
                    CountryCode = countryCode,
                    ExpireTime  = DateTime.UtcNow.AddSeconds(expireSeconds),
                    Type        = (int)EnumCaptchaType.Sms,
                    CreateTime  = DateTime.UtcNow,
                    Mobile      = phoneNumber,
                    State       = (int)EnumState.Normal
                };
                Create(entity, out var excutedResult);
                if (excutedResult.Status != EnumStatus.Success)
                {
                    return(ExcutedResult <string> .FailedResult(excutedResult.Code, excutedResult.Message));
                }

                #region 新版短信
                //短信模板
                var templateCode = "";
                if (!countryCode.Contains("86"))
                {
                    templateCode = _configDataLogic.GetByKey(ConfigDataKey.EnSmsTemplate);
                }
                else
                {
                    templateCode = _configDataLogic.GetByKey(ConfigDataKey.SmsTemplate);
                }
                //短信渠道
                SmsClient smsClient = AspectCoreContainer.Resolve <YunPianSmsClient>();
                string    content   = string.Format(templateCode, captcha);
                int       client    = 1;//固定传web
                excutedResult = await smsClient.SendAsync(phoneNumber, content, client, countryCode, templateCode);

                if (excutedResult.Status != EnumStatus.Success || excutedResult.Code != SysResultCode.Success)
                {
                    return(ExcutedResult <string> .FailedResult(excutedResult.Code, excutedResult.Message));
                }
                #endregion
                return(ExcutedResult <string> .SuccessResult("", entity.Id.ToString()));
            }
            catch (Exception ex)
            {
                Log4NetHelper.WriteError(GetType(), ex, "发送验证码错误");
                throw;
            }
        }
        public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            var identity = context.RouteData.Values["controller"] + "/" + context.RouteData.Values["action"];

            if (!context.Filters.Contains(new IgnoreAttribute()))
            {
                var repository =
                    AspectCoreContainer.Resolve <ISysMenuRepository>();
                if (repository.Count(
                        m => m.Identity.Equals(identity, StringComparison.OrdinalIgnoreCase) && m.Activable) <= 0)
                {
                    if (context.HttpContext.Request.IsAjaxRequest())
                    {
                        context.Result = new JsonResult(new { success = false, msg = "您请求的地址不存在,或者已被停用." });
                    }
                    else
                    {
                        context.Result = new ViewResult()
                        {
                            ViewName = "NotFound"
                        };
                        context.HttpContext.Response.StatusCode = HttpStatusCode.NotFound.GetHashCode();
                    }
                }
            }

            await base.OnActionExecutionAsync(context, next);
        }
示例#8
0
        public static IApplicationBuilder UseQuartz(this IApplicationBuilder app)
        {
            var startup = AspectCoreContainer.Resolve <QuartzStartup>();

            startup?.Init();
            return(app);
        }
示例#9
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, option =>
            {
                option.LoginPath        = "/SignIn";
                option.AccessDeniedPath = "/Home/Error";
                option.Cookie.HttpOnly  = true;
            });

            services.Configure <DbContextOption>(Configuration.GetSection("ConnectionStrings"));

            //services.AddSingleton(Configuration);
            services.AddScopedAssembly("Agile.Repository");
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();//用于获取请求上下文
            services.AddMvc(option =>
            {
                option.Filters.Add(new GlobalExceptionFilter());
            }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            return(AspectCoreContainer.BuildServiceProvider(services));
        }
示例#10
0
        public void TestGetDataTableListForPostgreSql()
        {
            BuildServiceForPostgreSql();
            var dbContext = AspectCoreContainer.Resolve <IDbContextCore>();
            var tables    = dbContext.GetCurrentDatabaseTableList();

            Assert.IsNotNull(tables);
        }
示例#11
0
        public IServiceProvider BuildServiceForMongoDB()
        {
            IServiceCollection services = new ServiceCollection();

            //在这里注册EF上下文
            services = RegisterMongoDbContext(services);
            services.AddOptions();
            return(AspectCoreContainer.BuildServiceProvider(services)); //接入AspectCore.Injector
        }
示例#12
0
        /// <summary>
        /// IoC初始化
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        private IServiceProvider InitIoC(IServiceCollection services)
        {
            services.AddOptions();
            services.AddMvc(option => { option.Filters.Add(new GlobalExceptionFilter()); })
            .SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
            .AddControllersAsServices();

            return(AspectCoreContainer.BuildServiceProvider(services)); //接入AspectCore.Injector
        }
示例#13
0
        public override Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            var request = context.HttpContext.Request;

            if (request.Method == "POST")
            {
                IHttpContextAccessor httpContextAccessor = AspectCoreContainer.CreateScope().Resolve <IHttpContextAccessor>();
                var configDataLogic = AspectCoreContainer.CreateScope().Resolve <IConfigDataLogic>();
                var ip                    = httpContextAccessor.HttpContext.GetRequestIp4Address()?.ToString();
                var ipWhiteList           = configDataLogic.GetByKey(ConfigDataKey.IpWhiteList);
                var timestampOffsetMinute = configDataLogic.GetByKey(ConfigDataKey.TimestampOffsetMinute);
                double.TryParse(timestampOffsetMinute, out var minute);
                var actionParams = StreamHelper.GetStreamText(request.Body);
                Dictionary <string, object> jsonDict = JsonConvert.DeserializeObject <Dictionary <string, Object> >(actionParams);
                var d          = new SortedDictionary <string, object>(jsonDict);
                var sss        = JsonConvert.SerializeObject(d);
                var timeHeader = request.Headers["timestamp"].ToString();
                var signHeader = request.Headers["sign"].ToString();
                if (timeHeader == "" || signHeader == "")
                {
                    context.Result = new JsonResult(ExcutedResult.FailedResult(BusinessResultCode.NoSign, "调用错误"));
                }
                else
                {
                    if (long.TryParse(timeHeader, out var timestamp))
                    {
                        var time = DateTimeHelper.ConvertFromTimeStamp(timestamp);
                        if (time == null || time.Value.AddMinutes(minute).ToUniversalTime() < DateTime.UtcNow)
                        {
                            context.Result = new JsonResult(ExcutedResult.FailedResult(BusinessResultCode.NoSign, "调用错误"));
                        }
                        var sign = ShaHelper.Encrypt(sss + timeHeader);
                        if (sign != signHeader)
                        {
                            context.Result = new JsonResult(ExcutedResult.FailedResult(BusinessResultCode.SignError, "签名错误"));
                        }
                    }
                    else
                    {
                        context.Result = new JsonResult(ExcutedResult.FailedResult(BusinessResultCode.NoSign, "调用错误"));
                    }
                }


                if (!string.IsNullOrEmpty(ipWhiteList))
                {
                    if (!string.IsNullOrEmpty(ip) && !ipWhiteList.Contains(ip))
                    {
                        context.Result =
                            new JsonResult(ExcutedResult.FailedResult(SysResultCode.ServerException, "Your ip not access"));
                    }
                }
            }

            return(base.OnActionExecutionAsync(context, next));
        }
示例#14
0
        public static async void WhileUpdatingAsync(IUpdatingEntry <SysMenu, DbContext> entry)
        {
            using (var service = AspectCoreContainer.Resolve <ISysMenuRepository>())
            {
                var parentMenu = await service.GetSingleAsync(entry.Entity.ParentId);

                entry.Entity.SortIndex = entry.Entity.Id;
                entry.Entity.MenuPath  = (parentMenu?.MenuPath ?? "0") + "," + entry.Entity.Id;
            }
        }
示例#15
0
        public static ICodeFirst CodeFirst(this IDbContextCore dbContext)
        {
            var codeFirst = AspectCoreContainer.Resolve <ICodeFirst>();

            if (codeFirst == null)
            {
                throw new Exception("请先在Startup.cs文件的ConfigureServices方法中调用UseCodeGenerator方法以注册。");
            }
            return(codeFirst);
        }
示例#16
0
        public void GenerateAll(bool ifExsitedCovered = false)
        {
            var option = AspectCoreContainer.Resolve <IOptions <CodeGenerateOption> >().Value;

            if (option == null)
            {
                throw new Exception("请先注入CodeGenerateOption");
            }
            Instance = new CodeGenerator(option);
        }
示例#17
0
        /// <summary>
        /// 根据数据表生成Model层、Controller层、IRepository层和Repository层代码
        /// </summary>
        /// <param name="ifExsitedCovered">是否覆盖已存在的同名文件</param>
        /// <param name="selector"></param>
        internal void GenerateAllCodesFromDatabase(bool ifExsitedCovered = false, Func <DbTable, bool> selector = null)
        {
            var dbContext = AspectCoreContainer.Resolve <IDbContextCore>();

            if (dbContext == null)
            {
                throw new Exception("未能获取到数据库上下文,请先注册数据库上下文。");
            }
            GenerateAllCodesFromDatabase(dbContext, ifExsitedCovered, selector);
        }
示例#18
0
        public void TestGetDataTableForSqlServer()
        {
            BuildServiceForSqlServer();
            var dbContext = AspectCoreContainer.Resolve <IDbContextCore>();
            var dt1       = dbContext.GetCurrentDatabaseAllTables();

            foreach (DataRow row in dt1.Rows)
            {
                var dt2 = dbContext.GetTableColumns(row["TableName"].ToString());
            }
        }
示例#19
0
 public AccountLogic(IAccountRepository repository, IConfigDataLogic configDataLogic,
                     ICreateAccountRecordRepository createAccountRecordRepository, ITokensLogic tokensLogic,
                     IHostingEnvironment env, IConfiguration config) : base(repository)
 {
     _contractFactory = (ContractClientFactory)AspectCoreContainer.CreateScope().Resolve(typeof(ContractClientFactory));
     _configDataLogic = configDataLogic;
     _tokensLogic     = tokensLogic;
     _createAccountRecordRepository = createAccountRecordRepository;
     Environment = env;
     _config     = config;
     _filePreUrl = _config["FilePreUrl"];
 }
示例#20
0
        public void TestCsRedisClient()
        {
            BuildServiceForSqlServer();
            var dbContext = AspectCoreContainer.Resolve <IDbContextCore>();

            RedisHelper.Set("test_cache_key", JsonConvertor.Serialize(dbContext.GetCurrentDatabaseTableList()),
                            10 * 60);
            Thread.Sleep(2000);
            var content = DistributedCacheManager.Get("test_cache_key");

            Assert.IsNotNull(content);
        }
示例#21
0
        public static async void AfterInsertedAsync(IInsertedEntry <SysMenu, DbContext> entry)
        {
            using (var service = AspectCoreContainer.Resolve <ISysMenuRepository>())
            {
                var parentMenu = await service.GetSingleAsync(entry.Entity.ParentId);

                entry.Entity.MenuPath  = (parentMenu?.MenuPath ?? "0") + "," + entry.Entity.Id;
                entry.Entity.SortIndex = entry.Entity.Id;
                service.Update(entry.Entity, false, "MenuPath", "SortIndex");
                await DistributedCacheManager.RemoveAsync("Redis_Cache_SysMenu");//插入成功后清除缓存以更新
            }
        }
示例#22
0
 public static IServiceProvider BuildAspectCoreServiceProvider(this IServiceCollection services,
                                                               Action <IAspectConfiguration> configure = null)
 {
     if (configure == null)
     {
         configure = config =>
         {
             config.Interceptors.AddTyped <FromDbContextFactoryInterceptor>();
         };
     }
     return(ServiceLocator.Current = AspectCoreContainer.BuildServiceProvider(services, configure));
 }
示例#23
0
        /// <summary>
        /// 渲染视图
        /// </summary>
        protected async Task <string> RenderToStringAsync(ResultExecutingContext context)
        {
            string viewName = "";
            object model    = null;
            bool   isPage   = false;

            if (context.Result is ViewResult result)
            {
                viewName = result.ViewName;
                viewName = string.IsNullOrWhiteSpace(viewName) ? context.RouteData.Values["action"].SafeString() : viewName;
                model    = result.Model;
            }

            if (context.Result is PageResult pageResult)
            {
                if (context.ActionDescriptor is PageActionDescriptor pageActionDescriptor)
                {
                    isPage   = true;
                    model    = pageResult.Model;
                    viewName = pageActionDescriptor.RelativePath;
                }
            }
            var razorViewEngine     = AspectCoreContainer.Resolve <IRazorViewEngine>();
            var compositeViewEngine = AspectCoreContainer.Resolve <ICompositeViewEngine>();
            var tempDataProvider    = AspectCoreContainer.Resolve <ITempDataProvider>();
            var serviceProvider     = AspectCoreContainer.Resolve <IServiceProvider>();
            var httpContext         = new DefaultHttpContext {
                RequestServices = serviceProvider
            };
            var actionContext = new ActionContext(httpContext, context.RouteData, new ActionDescriptor());

            using (var stringWriter = new StringWriter())
            {
                var viewResult = isPage
                    ? GetView(compositeViewEngine, viewName)
                    : GetView(razorViewEngine, actionContext, viewName);
                if (viewResult.View == null)
                {
                    throw new ArgumentNullException($"未找到视图: {viewName}");
                }
                var viewDictionary = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary())
                {
                    Model = model
                };
                var viewContext = new ViewContext(actionContext, viewResult.View, viewDictionary, new TempDataDictionary(actionContext.HttpContext, tempDataProvider), stringWriter, new HtmlHelperOptions());
                await viewResult.View.RenderAsync(viewContext);

                return(stringWriter.ToString());
            }
        }
示例#24
0
        /// <summary>
        /// 获取物理路径
        /// </summary>
        /// <param name="relativePath">相对路径</param>
        public static string GetPhysicalPath(string relativePath)
        {
            if (string.IsNullOrWhiteSpace(relativePath))
            {
                return(string.Empty);
            }
            var rootPath = AspectCoreContainer.Resolve <IHostingEnvironment>()?.ContentRootPath;

            if (string.IsNullOrWhiteSpace(rootPath))
            {
                return(System.IO.Path.GetFullPath(relativePath));
            }
            return($"{rootPath}\\{relativePath.Replace("/", "\\").TrimStart('\\')}");
        }
示例#25
0
        public static FileModel FileHeaderToModel(FileHeader fileHeader)
        {
            IConfiguration config     = AspectCoreContainer.Resolve <IConfiguration>();
            var            filePreUrl = config["FilePreUrl"];

            return(new FileModel
            {
                Id = fileHeader.Id.ToString(),
                FileExt = fileHeader.FileExt,
                Category = fileHeader.Category,
                Size = fileHeader.Length,
                FileUrl = $"{filePreUrl}{fileHeader.Id}?tag=client_upload"
            });
        }
示例#26
0
 public static void WhileUpdating(IUpdatingEntry <SysMenu, DbContext> entry)
 {
     using (var service = AspectCoreContainer.Resolve <ISysMenuRepository>())
     {
         var parentMenu = service.GetSingle(entry.Entity.ParentId);
         if (string.IsNullOrEmpty(parentMenu?.MenuPath))
         {
             entry.Entity.MenuPath = entry.Entity.Id;
         }
         else
         {
             entry.Entity.MenuPath = parentMenu.MenuPath + "," + entry.Entity.Id;
         }
     }
 }
示例#27
0
 public IActionResult DbCreate()
 {
     try
     {
         //生成数据库表
         SugarDbContext db = new SugarDbContext();
         db.GetInstance().CodeFirst.SetStringDefaultLength(20).InitTables(typeof(MenuInfo), typeof(UserInfo), typeof(UserRelationRole), typeof(UserRoleInfo), typeof(UserRoleRelateMenu));
         var o = AspectCoreContainer.Resolve <IOptions <DbContextOption> >();
         return(Json(new { result = "成功生成数据库表", option = o.Value }));
     }
     catch (Exception e)
     {
         return(Json(new { result = "生成数据库表失败", message = e.Message }));
     }
 }
示例#28
0
        public void TestForMongoDb()
        {
            BuildServiceForMongoDB();
            var context = AspectCoreContainer.Resolve <IDbContextCore>();

            Assert.IsTrue(context.Add(new MongoModel()
            {
                Age      = 28,
                Birthday = Convert.ToDateTime("1999-01-22"),
                IsBitch  = false,
                UserName = "******",
                Wage     = 100000000
            }) > 0);
            context.Dispose();
        }
        /// <summary>
        /// 静态构造函数:从IoC容器读取配置参数,如果读取失败则会抛出ArgumentNullException异常
        /// </summary>
        static CodeGenerator()
        {
            options = AspectCoreContainer.Resolve <IOptions <CodeGenerateOption> >();
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }
            var path = AppDomain.CurrentDomain.BaseDirectory;
            var flag = path.IndexOf("/bin");

            if (flag > 0)
            {
                Delimiter = "/";//如果可以取到值,修改分割符
            }
        }
示例#30
0
        public IServiceProvider BuildServiceForSqlServer()
        {
            IServiceCollection services = new ServiceCollection();

            //在这里注册EF上下文
            services = RegisterSqlServerContext(services);
            services.Configure <CodeGenerateOption>(options =>
            {
                options.ModelsNamespace        = "Models";
                options.IRepositoriesNamespace = "IRepository";
                options.RepositoriesNamespace  = "Repository";
                options.OutputPath             = "D:\\VSCode\\Demo\\AutoGenerateCode";
            });
            services.AddOptions();
            return(AspectCoreContainer.BuildServiceProvider(services)); //接入AspectCore.Injector
        }