示例#1
0
        public ITestService GetClient <T>()
        {
            if (Client == null)
            {
                string ipStr = Appsettings.GetSettingNode(new string[] { "Grpc", "Ip" });
                int    port  = Appsettings.GetSettingNodeValue <int>(Convert.ToInt32, 0, new string[] { "Grpc", "Port" });

                if (string.IsNullOrEmpty(ipStr) || port == 0)
                {
                    throw new Exception("appsettings 中没有对 grpc的ip或端口没有进行相关的配置!");
                }
                var channel = new Channel("localhost", port, ChannelCredentials.Insecure);
                Client = MagicOnionClient.Create <ITestService>(channel);
            }

            return(Client);
        }
示例#2
0
        /// <summary>
        /// 在自定义策略处理器中调用方法
        /// </summary>
        /// <param name="roleArr"></param>
        /// <returns></returns>
        public async Task <List <RoleActionModel> > GetRoleAction(Guid [] roleArr)
        {
            var RoleModuleList = new List <RoleActionModel>();
            var Rolelist       = await _roleRepositoty.GetAllListAsync(x => roleArr.Contains(x.Id));                             //根据Httpcontext存储的角色名称获取角色ID

            var RoleAssig = await _roleRightAssigRepository.GetAllListAsync(x => Rolelist.Select(s => s.Id).Contains(x.RoleId)); //根据角色ID获取到所有的权限

            var Btnlist = await _buttonRepositoty.GetAllListAsync(x => x.IsDrop == false);                                       //获取所有的按钮

            List <SysMenu> Menulist = new List <SysMenu>();

            if (await _redisCacheManager.Get(Appsettings.app(new string[] { "CacheOptions", "Menukey" })))                          //判断菜单缓存是否存在,如果存在则取缓存不存在则取数据库
            {
                Menulist = await _redisCacheManager.GetList <SysMenu>(Appsettings.app(new string[] { "CacheOptions", "Menukey" })); //.Where(x=>MenuIds.Contains(x.Id)).ToList();
            }
            else
            {
                Menulist = await this._menuRepositoty.GetAll(x => x.IsDrop == false).AsNoTracking().ToListAsync();

                await _redisCacheManager.Set(Appsettings.app(new string[] { "CacheOptions", "Menukey" }), Menulist);
            }
            if (!Menulist.Any())
            {
                Menulist = await _menuRepositoty.GetAllListAsync(x => x.IsDrop == false);//根据菜单ID获取菜单列表 x=>MenuIds.Contains(x.Id)
            }
            foreach (var item in RoleAssig)
            {
                var RoleModel = Rolelist.Where(x => x.Id == item.RoleId).FirstOrDefault(); //获取角色实体
                var MenuModel = Menulist.Where(x => x.Id == item.MenuId).FirstOrDefault(); //获取菜单实体
                RoleModuleList.Add(new RoleActionModel {
                    RoleName = RoleModel.Id, ActionName = MenuModel.APIAddress
                });
                if (!item.ButtonIds.IsNullOrEmpty()) //判断是否存在按钮
                {
                    List <Guid> guids   = new List <Guid>();
                    var         btnArr  = item.ButtonIds.Split(',').Select(x => x.ToGuid()).ToList();
                    var         RoleBtn = Btnlist.Where(x => btnArr.Contains(x.Id)).ToList();
                    RoleModuleList.AddRange(RoleBtn.Select(x => new RoleActionModel
                    {
                        RoleName   = RoleModel.Id,//在这里代表的是
                        ActionName = x.APIAddress,
                    }));
                }
            }
            return(RoleModuleList);
        }
示例#3
0
        public static (List <MutiDBOperate>, List <MutiDBOperate>) MutiInitConn()
        {
            List <MutiDBOperate> listdatabase = Appsettings.app <MutiDBOperate>("DBS")
                                                .Where(i => i.Enabled).ToList();

            foreach (var i in listdatabase)
            {
                SpecialDbString(i);
            }
            List <MutiDBOperate> listdatabaseSimpleDB = new List <MutiDBOperate>(); //单库
            List <MutiDBOperate> listdatabaseSlaveDB  = new List <MutiDBOperate>(); //从库

            // 单库,且不开启读写分离,只保留一个
            if (!Appsettings.app(new string[] { "CQRSEnabled" }).ObjToBool() && !Appsettings.app(new string[] { "MutiDBEnabled" }).ObjToBool())
            {
                if (listdatabase.Count == 1)
                {
                    return(listdatabase, listdatabaseSlaveDB);
                }
                else
                {
                    var dbFirst = listdatabase.FirstOrDefault(d => d.ConnId == Appsettings.app(new string[] { "MainDB" }).ObjToString());
                    if (dbFirst == null)
                    {
                        dbFirst = listdatabase.FirstOrDefault();
                    }
                    listdatabaseSimpleDB.Add(dbFirst);
                    return(listdatabaseSimpleDB, listdatabaseSlaveDB);
                }
            }


            // 读写分离,且必须是单库模式,获取从库
            if (Appsettings.app(new string[] { "CQRSEnabled" }).ObjToBool() && !Appsettings.app(new string[] { "MutiDBEnabled" }).ObjToBool())
            {
                if (listdatabase.Count > 1)
                {
                    listdatabaseSlaveDB = listdatabase.Where(d => d.ConnId != Appsettings.app(new string[] { "MainDB" }).ObjToString()).ToList();
                }
            }



            return(listdatabase, listdatabaseSlaveDB);
            //}
        }
        /// <summary>
        /// 颁发JWT字符串
        /// </summary>
        /// <param name="tokenModel"></param>
        /// <returns></returns>
        public static string IssueJwt(TokenModelJwt tokenModel)
        {
            // 自己封装的 appsettign.json 操作类,看下文
            string iss    = Appsettings.app(new string[] { "Audience", "Issuer" });
            string aud    = Appsettings.app(new string[] { "Audience", "Audience" });
            string secret = Appsettings.app(new string[] { "Audience", "Secret" });

            var claims = new List <Claim>
            {
                /*
                 * 特别重要:
                 * 1、这里将用户的部分信息,比如 uid 存到了Claim 中,如果你想知道如何在其他地方将这个 uid从 Token 中取出来,请看下边的SerializeJwt() 方法,或者在整个解决方案,搜索这个方法,看哪里使用了!
                 * 2、你也可以研究下 HttpContext.User.Claims ,具体的你可以看看 Policys/PermissionHandler.cs 类中是如何使用的。
                 */

                new Claim(JwtRegisteredClaimNames.Jti, tokenModel.Uid.ToString()),
                new Claim(JwtRegisteredClaimNames.Iat, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),
                new Claim(JwtRegisteredClaimNames.Nbf, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),
                //这个就是过期时间,目前是过期1000秒,可自定义,注意JWT有自己的缓冲过期时间
                new Claim(JwtRegisteredClaimNames.Exp, $"{new DateTimeOffset(DateTime.Now.AddSeconds(1000)).ToUnixTimeSeconds()}"),
                new Claim(JwtRegisteredClaimNames.Iss, iss),
                new Claim(JwtRegisteredClaimNames.Aud, aud),

                //new Claim(ClaimTypes.Role,tokenModel.Role),//为了解决一个用户多个角色(比如:Admin,System),用下边的方法
            };

            // 可以将一个用户的多个角色全部赋予;
            // 作者:DX 提供技术支持;
            claims.AddRange(tokenModel.Role.Split(',').Select(s => new Claim(ClaimTypes.Role, s)));


            //秘钥 (SymmetricSecurityKey 对安全性的要求,密钥的长度太短会报出异常)
            var key   = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var jwt = new JwtSecurityToken(
                issuer: iss,
                claims: claims,
                signingCredentials: creds);

            var jwtHandler = new JwtSecurityTokenHandler();
            var encodedJwt = jwtHandler.WriteToken(jwt);

            return(encodedJwt);
        }
示例#5
0
        static async Task MainAsync(string[] args)
        {
            var builder = new ConfigurationBuilder()
                          .AddJsonFile("appsettings.json")
                          .AddJsonFile("appsettings.local.json", true);
            var configuration = builder.Build();

            var connectionString = configuration.GetConnectionString("DefaultConnection");

            if (string.IsNullOrEmpty(connectionString))
            {
                //Indicates that a connection string was not provided in the appsettings file
                throw new InvalidOperationException("A connection string must be configured");
            }

            //Configure database
            var optionsBuilder = new DbContextOptionsBuilder();
            var dbOptions      = optionsBuilder
                                 .UseSqlServer(connectionString, providerOptions => providerOptions.CommandTimeout(60))
                                 .UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking)
                                 .Options;

            //Bind to typed config objects
            var appsettings                = new Appsettings();
            var friendsParserSettings      = new EntityParserSettings();
            var timelinePostParserSettings = new EntityParserSettings();

            configuration.GetSection("Appsettings").Bind(appsettings);
            configuration.GetSection("FriendsParserSettings").Bind(friendsParserSettings);
            configuration.GetSection("TimelinePostParserSettings").Bind(timelinePostParserSettings);

            //Process parsing of export
            using (var dbContext = new FacebookExportEntities.FacebookExportDbContext(dbOptions))
            {
                //Parse friends
                var friendsFilePath = Path.Combine(appsettings.FacebookExportPath, friendsParserSettings.FilePath);
                var friendsParser   = new FriendsParser(dbContext, friendsFilePath, friendsParserSettings);
                await friendsParser.ProcessImport();

                //Parse timeline posts
                var timelinePostsPath  = Path.Combine(appsettings.FacebookExportPath, timelinePostParserSettings.FilePath);
                var timelinePostParser = new TimelinePostParser(dbContext, timelinePostsPath, timelinePostParserSettings);
                await timelinePostParser.ProcessImport();
            }
        }
示例#6
0
        public async Task <MessageModel <AccessApiDateView> > GetIds4Users()
        {
            List <ApiDate> apiDates = new List <ApiDate>();

            if (Appsettings.app(new string[] { "MutiDBEnabled" }).ObjToBool())
            {
                var users = await _applicationUserServices.Query(d => d.tdIsDelete == false);

                apiDates = (from n in users
                            group n by new { n.birth.Date } into g
                            select new ApiDate
                {
                    date = g.Key?.Date.ToString("yyyy-MM-dd"),
                    count = g.Count(),
                }).ToList();

                apiDates = apiDates.OrderByDescending(d => d.date).Take(30).ToList();
            }


            if (apiDates.Count == 0)
            {
                apiDates.Add(new ApiDate()
                {
                    date  = "没数据,或未开启相应接口服务",
                    count = 0
                });
            }
            //return new MessageModel<AccessApiDateView>()
            //{
            //    msg = "获取成功",
            //    success = true,
            //    response = new AccessApiDateView
            //    {
            //        columns = new string[] { "date", "count" },
            //        rows = apiDates.OrderBy(d => d.date).ToList(),
            //    }
            //};

            return(Success(new AccessApiDateView
            {
                columns = new string[] { "date", "count" },
                rows = apiDates.OrderBy(d => d.date).ToList(),
            }, "获取成功"));
        }
示例#7
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            services.AddSingleton(new Appsettings(Environment.ContentRootPath));


            //注入Ocelot 配置信息

            //版本一  Ocelot GeteWay
            //services.AddOcelot(new ConfigurationBuilder()
            //        .AddJsonFile("configuration.json")
            //        .Build());

            // specified IdentityServer 4 configuration
            #region IdentityServerAuthenticationOptions => need to refactor
            Action <IdentityServerAuthenticationOptions> isaOptClient = option =>
            {
                option.Authority            = Appsettings.app(new string[] { "Idps", "AuthorityUrl" });
                option.ApiName              = Appsettings.app(new string[] { "Idps", "ApiNames", "ValuesServiceName" });
                option.RequireHttpsMetadata = Appsettings.app(new string[] { "Idps", "RequireHttps" }).ObjToBool();
                //option.SupportedTokens = SupportedTokens.Both;
                option.ApiSecret = Appsettings.app(new string[] { "Idps", "ApiNames", "ValuesServiceName" });
            };

            Action <IdentityServerAuthenticationOptions> isaOptProduct = option =>
            {
                option.Authority            = Appsettings.app(new string[] { "Idps", "AuthorityUrl" });
                option.ApiName              = Appsettings.app(new string[] { "Idps", "ApiNames", "ProductServiceName" });
                option.RequireHttpsMetadata = Appsettings.app(new string[] { "Idps", "RequireHttps" }).ObjToBool();
                //option.SupportedTokens = SupportedTokens.Both;
                option.ApiSecret = Appsettings.app(new string[] { "Idps", "ApiNames", "ProductService" });
            };
            #endregion

            services.AddAuthentication()
            .AddIdentityServerAuthentication("ValuesServiceKey", isaOptClient)
            .AddIdentityServerAuthentication("ProductServiceKey", isaOptProduct);


            //版本二  Ocelot GeteWay+Consul
            services.AddOcelot(new ConfigurationBuilder()
                               .AddJsonFile("configuration.json")
                               .Build()).AddConsul().AddPolly();
        }
示例#8
0
        /// <summary>
        /// Delete Messages
        /// </summary>
        /// <returns></returns>
        public async Task DeleteMessagesAsync()
        {
            var a = new Appsettings();

            await using var queueClient = new ServiceBusClient(Appsettings.app("ServiceBus", "PrimaryConnectionString"));
            try
            {
                // create a receiver that we can use to receive the message
                ServiceBusReceiver        receiver      = queueClient.CreateReceiver(Appsettings.app("ServiceBus", "QueueName"));
                ServiceBusReceivedMessage peekedMessage = await receiver.ReceiveMessageAsync();

                await receiver.CompleteMessageAsync(peekedMessage);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
示例#9
0
        public UnitOfWork(List <ISqlSugarClient> sqlSugarClients)
        {
            // 每次取最上边的db,这个顺序已经在注册服务的时候,切换好了
            _sqlSugarClient = sqlSugarClients[0];

            if (Appsettings.app(new string[] { "AppSettings", "SqlAOP", "Enabled" }).ObjToBool())
            {
                _sqlSugarClient.Aop.OnLogExecuting = (sql, pars) => //SQL执行中事件
                {
                    Parallel.For(0, 1, e =>
                    {
                        MiniProfiler.Current.CustomTiming("SQL:", GetParas(pars) + "【SQL语句】:" + sql);
                        LogLock.OutSql2Log("SqlLog", new string[] { GetParas(pars), "【SQL语句】:" + sql });
                    });
                };
            }
            _sqlSugarClients = sqlSugarClients;
        }
示例#10
0
        public static void AddSqlsugarSetup(this IServiceCollection services)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            services.AddScoped <SqlSugar.ISqlSugarClient>(o =>
            {
                return(new SqlSugar.SqlSugarClient(new SqlSugar.ConnectionConfig()
                {
                    ConnectionString = Appsettings.app(new string[] { "DataBases", "MySql", "ConnectionString" }),
                    DbType = SqlSugar.DbType.MySql,
                    IsAutoCloseConnection = true,
                    InitKeyType = SqlSugar.InitKeyType.SystemTable
                }));
            });
        }
示例#11
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton(new Appsettings(Environment.ContentRootPath));

            services.AddAuthentication(AzureADB2CDefaults.AuthenticationScheme)
            .AddAzureADB2C(options =>
            {
                options.Instance              = Appsettings.app("Azure_AD_B2C", "Instance");
                options.ClientId              = Appsettings.app("Azure_AD_B2C", "ClientId");
                options.CallbackPath          = Appsettings.app("Azure_AD_B2C", "CallbackPath");
                options.Domain                = Appsettings.app("Azure_AD_B2C", "Domain");
                options.SignUpSignInPolicyId  = Appsettings.app("Azure_AD_B2C", "SignUpSignInPolicyId");
                options.ResetPasswordPolicyId = Appsettings.app("Azure_AD_B2C", "ResetPasswordPolicyId");
                options.EditProfilePolicyId   = Appsettings.app("Azure_AD_B2C", "EditProfilePolicyId");
            });

            services.AddControllersWithViews();
        }
示例#12
0
 public RabbitServer()
 {
     try
     {
         connectionFactory = new ConnectionFactory()
         {
             UserName = Appsettings.app(new string[] { "RabbitMQConfig", "UserName" }),
             Password = Appsettings.app(new string[] { "RabbitMQConfig", "Password" }),
             HostName = Appsettings.app(new string[] { "RabbitMQConfig", "HostName" }),
             AutomaticRecoveryEnabled = Convert.ToBoolean(Appsettings.app(new string[] { "RabbitMQConfig", "AutomaticRecoveryEnabled" })),
             TopologyRecoveryEnabled  = Convert.ToBoolean(Appsettings.app(new string[] { "RabbitMQConfig", "TopologyRecoveryEnabled" })),
         };
     }
     catch (Exception)
     {
         throw;
     }
 }
示例#13
0
        /// <summary>
        /// Swagger 中间件
        /// </summary>
        /// <param name="app"></param>
        /// <param name="pathBase"></param>
        public static void UseSwagger(this IApplicationBuilder app, string pathBase)
        {
            var ApiName = Appsettings.app(new string[] { "Startup", "ApiName" });

            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                typeof(ApiVersions).GetEnumNames().OrderByDescending(e => e).ToList().ForEach(version =>
                {
                    c.SwaggerEndpoint($"/swagger/{version}/swagger.json", $"{ApiName} {version}");
                    //接口折叠起来
                    c.DocExpansion(DocExpansion.None);
                });
                //c.RoutePrefix = "";
                //嵌入静态资源 如果扩展UI 的话可以考虑使用
                //c.IndexStream = () => GetType().GetTypeInfo().Assembly.GetManifestResourceStream("ZQCY.Appointment.Extensions.index.html");
            });
        }
示例#14
0
        /// <summary>
        /// 颁发JWT字符串
        /// </summary>
        /// <param name="tokenModel"></param>
        /// <returns></returns>
        public static async Task <string> IssueJwt(TokenModelJwt tokenModel)
        {
            return(await Task.Run(() =>
            {
                string iss = Appsettings.app(new string[] { "Audience", "Issuer" });
                string aud = Appsettings.app(new string[] { "Audience", "Audience" });
                string secret = Appsettings.app(new string[] { "Audience", "Secret" });

                //var claims = new Claim[] //old
                var claims = new List <Claim>
                {
                    //下边为Claim的默认配置
                    new Claim(JwtRegisteredClaimNames.Jti, tokenModel.Uid.ToString()),
                    new Claim(JwtRegisteredClaimNames.Iat, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),
                    new Claim(JwtRegisteredClaimNames.Nbf, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),
                    //这个就是过期时间,目前是过期100秒,可自定义,注意JWT有自己的缓冲过期时间
                    new Claim(JwtRegisteredClaimNames.Exp, $"{new DateTimeOffset(DateTime.Now.AddSeconds(100)).ToUnixTimeSeconds()}"),
                    new Claim(JwtRegisteredClaimNames.Iss, iss),
                    new Claim(JwtRegisteredClaimNames.Aud, aud),

                    //new Claim(ClaimTypes.Role,tokenModel.Role),//为了解决一个用户多个角色(比如:Admin,System),用下边的方法
                };

                // 可以将一个用户的多个角色全部赋予;
                // 作者:DX 提供技术支持;
                claims.AddRange(tokenModel.Role.Split(',').Select(s => new Claim(ClaimTypes.Role, s)));



                //秘钥 (SymmetricSecurityKey 对安全性的要求,密钥的长度太短会报出异常)
                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret));
                var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

                var jwt = new JwtSecurityToken(
                    issuer: iss,
                    claims: claims,
                    signingCredentials: creds);

                var jwtHandler = new JwtSecurityTokenHandler();
                var encodedJwt = jwtHandler.WriteToken(jwt);

                return encodedJwt;
            }));
        }
示例#15
0
        public static void AddRabbitMQSetup(this IServiceCollection services)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            if (Appsettings.App(new string[] { "RabbitMQ", "Enabled" }).ToBoolReq())
            {
                services.AddSingleton <IRabbitMQPersistentConnection>(sp =>
                {
                    var logger = sp.GetRequiredService <ILogger <RabbitMQPersistentConnection> >();

                    var factory = new ConnectionFactory()
                    {
                        HostName = Appsettings.App(new string[] { "RabbitMQ", "Connection" }),
                        DispatchConsumersAsync = true
                    };

                    if (!string.IsNullOrEmpty(Appsettings.App(new string[] { "RabbitMQ", "UserName" })))
                    {
                        factory.UserName = Appsettings.App(new string[] { "RabbitMQ", "UserName" });
                    }

                    if (!string.IsNullOrEmpty(Appsettings.App(new string[] { "RabbitMQ", "Password" })))
                    {
                        factory.Password = Appsettings.App(new string[] { "RabbitMQ", "Password" });
                    }

                    if (!string.IsNullOrEmpty(Appsettings.App(new string[] { "RabbitMQ", "Port" })))
                    {
                        factory.Port = Appsettings.App(new string[] { "RabbitMQ", "Port" }).ToInt32Req();
                    }

                    var retryCount = 5;
                    if (!string.IsNullOrEmpty(Appsettings.App(new string[] { "RabbitMQ", "RetryCount" })))
                    {
                        retryCount = Appsettings.App(new string[] { "RabbitMQ", "RetryCount" }).ToInt32Req();
                    }

                    return(new RabbitMQPersistentConnection(factory, logger, retryCount));
                });
            }
        }
示例#16
0
        public static int Run(ILogger logger, ResetOptions options)
        {
            try
            {
                Appsettings appsettings         = JsonConvert.DeserializeObject <Appsettings>(File.ReadAllText(Path.Combine(Directory.GetCurrentDirectory(), "appsettings.json")));
                bool        databaseInitialized = appsettings.ConnectionSettings != null;
                if (databaseInitialized)
                {
                    logger.LogInformation($"Try to reset \"{appsettings.ConnectionSettings.DatabaseName}\" database");
                }
                else
                {
                    logger.LogInformation($"Try to initialize project database");
                }

                SettingsUpdate.Run(logger, options);

                appsettings = JsonConvert.DeserializeObject <Appsettings>(File.ReadAllText(Path.Combine(Directory.GetCurrentDirectory(), "appsettings.json")));

                if (databaseInitialized)
                {
                    if (Drop.Run(logger, appsettings.ConnectionSettings) < 0)
                    {
                        throw new Exception("There was some errors with dropping database");
                    }
                }
                if (Create.Run(logger, appsettings.ConnectionSettings) < 0)
                {
                    throw new Exception("There was some errors with creating database");
                }
                if (MigrateUp.Run(logger, appsettings.ConnectionSettings) < 0)
                {
                    throw new Exception("There was some errors with migrating database");
                }

                logger.LogInformation($"{appsettings.ConnectionSettings.DatabaseName} database successfully reseted");
                return(0);
            }
            catch (Exception exception)
            {
                logger.LogError(exception.Message);
                return(1);
            }
        }
示例#17
0
        public async Task <List <BlogArticle> > GetBlogs()
        {
            var connect = Appsettings.app(new string[] { "AppSettings", "RedisCaching", "ConnectionString" });

            var blogArticleList = new List <BlogArticle>();

            if (redisCacheManager.Get <object>("Redis.Blog") != null)
            {
                blogArticleList = redisCacheManager.Get <List <BlogArticle> >("Redis.Blog");
            }
            else
            {
                blogArticleList = await blogArticleServices.Query(s => s.bID > 5);

                redisCacheManager.Set("Redis.Blog", blogArticleList, TimeSpan.FromHours(2));
            }

            return(blogArticleList);
        }
示例#18
0
        public async Task <List <Advertisement> > Get(int id)
        {
            var connect = Appsettings.app(new string[] { "AppSettings", "RedisCaching", "ConnectionString" });//按照层级的顺序,依次写出来

            var advertisementList = new List <Advertisement>();

            if (redisCacheManager.Get <object>("Redis.Doctor") != null)
            {
                advertisementList = redisCacheManager.Get <List <Advertisement> >("Redis.Doctor");
            }
            else
            {
                advertisementList = await advertisementServices.Query(d => d.Id == id);

                redisCacheManager.Set("Redis.Doctor", advertisementList, TimeSpan.FromHours(2));
            }

            return(advertisementList);
        }
示例#19
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddDbContext <PetroleumDbContext>(option =>
            {
                option.UseSqlServer(Appsettings.GetSectionValue("ConnectionString:Entities"));
            });

            #region ÅäÖÿçÓò
            services.AddCors(options => options.AddPolicy("cors", bulider =>
                                                          bulider.WithOrigins(Appsettings.GetSectionValue("AppSettings:CorsIPs").Split(','))
                                                          .AllowAnyMethod()
                                                          .AllowAnyHeader()
                                                          .AllowCredentials()
                                                          ));
            #endregion
            ////Senparc.CO2NET È«¾Ö×¢²á£¨±ØÐ룩
            //services.AddSenparcGlobalServices(Configuration);
        }
示例#20
0
        public static void AddRedisCacheSetup(this IServiceCollection services)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            services.AddTransient <IRedisBasketRepository, RedisBasketRepository>();

            services.AddSingleton <ConnectionMultiplexer>(sp =>
            {
                //获取连接字符串
                string redisConfiguration = Appsettings.app(new string[] { "Redis", "ConnectionString" });
                var configuration         = ConfigurationOptions.Parse(redisConfiguration, true);

                configuration.ResolveDns = true;
                return(ConnectionMultiplexer.Connect(configuration));
            });
        }
示例#21
0
        public static void AddTaskSetup(this IServiceCollection services)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            //ITaskJobService 构造需要 SchedulerCenter 在这里提前注入
            services.AddSingleton <ISchedulerCenter>();

            //任务是否需要开启
            if (!Appsettings.app("Middleware", "Job", "Enabled").ObjToBool())
            {
                return;
            }

            //services.AddTransient<AppointmentResourceJob>();
            //services.AddTransient<AppointmentOrderTimeOutJob>();
        }
示例#22
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            // 这种是自定义认证方案中间件(不建议)
            //app.UseMiddleware<AuthHelper.JwtTokenAuth>();

            // 启用Swagger服务
            app.UseSwagger();

            // 启用中间件服务对swagger-ui,指定swagger json终结点
            app.UseSwaggerUI(c => {
                // 根据版本号名称倒叙,遍历展示
                var ApiName = Appsettings.app("Startup", "ApiName");    // 获取appsettings.json配置文件中的串联节点的值:Bsam.Api

                typeof(ApiVersions).GetEnumNames().OrderByDescending(e => e).ToList().ForEach(version => {
                    c.SwaggerEndpoint($"/swagger/{version}/swagger.json", $"{ApiName} - {version}");
                });
                // 指定swagger ui 的首页,用这种反射方式指定资源流,C#中反射的资源需要设置index.html属性中【生成操作】为“嵌入的资源”,才能被以下反射方式获取到流
                // C#中资源的name的映射名字为:项目命名空间.资源文件所在文件夹名.资源文件名
                var basePath = AppContext.BaseDirectory;
                //c.IndexStream = () => GetType().GetTypeInfo().Assembly.GetManifestResourceStream("Bsam.Api.index.html");
                //c.InjectJavascript(@".\wwwroot\SwaggerUI\js\swagger.js");
                c.RoutePrefix = string.Empty;
            });


            app.UseCors("LimitRequests");

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();

                //endpoints.MapHub<ChatHub>("/api2/chatHub");
            });
        }
示例#23
0
        public static void AddOcr(this IServiceCollection services)
        {
            var ocrType = (OcrType)Appsettings.app("AppSettings", "Ocr", "OcrType").ToInt();

            switch (ocrType)
            {
            case OcrType.Baidu:
                services.AddScoped <IOcr, BaiduOcr>();
                break;

            case OcrType.Aliyun:
                services.AddScoped <IOcr, AliyunOcr>();
                break;

            case OcrType.Tencent:
                services.AddScoped <IOcr, TencentOcr>();
                break;
            }
        }
示例#24
0
        public static void AddSqlsugarSetup(this IServiceCollection services)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            // 默认添加主数据库连接
            MainDb.CurrentDbConnId = Appsettings.app(new string[] { "MainDB" });

            // 把多个连接对象注入服务,这里必须采用Scope,因为有事务操作
            services.AddScoped <ISqlSugarClient>(o =>
            {
                var listConfig = new List <ConnectionConfig>();

                BaseDBConfig.MutiConnectionString.ForEach(m =>
                {
                    listConfig.Add(new ConnectionConfig()
                    {
                        ConfigId              = m.ConnId.ObjToString().ToLower(),
                        ConnectionString      = m.Conn,
                        DbType                = (DbType)m.DbType,
                        IsAutoCloseConnection = true,
                        IsShardSameThread     = false,
                        AopEvents             = new AopEvents
                        {
                            OnLogExecuting = (sql, p) =>
                            {
                                // 多库操作的话,此处暂时无效果,在另一个地方有效,具体请查看BaseRepository.cs
                            }
                        },
                        MoreSettings = new ConnMoreSettings()
                        {
                            IsAutoRemoveDataCache = true
                        }
                        //InitKeyType = InitKeyType.SystemTable
                    }
                                   );
                });
                return(new SqlSugarClient(listConfig));
            });
        }
示例#25
0
        /// <summary>
        /// Cors 跨域资源共享
        /// </summary>
        /// <param name="services"></param>
        public static void AddCorsSetup(this IServiceCollection services)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            services.AddCors(c =>
            {
                if (!Appsettings.App(new string[] { "Startup", "Cors", "EnableAllIPs" }).ToBoolReq())
                {
                    c.AddPolicy(Appsettings.App(new string[] { "Startup", "Cors", "PolicyName" }),
                                policy =>
                    {
                        policy
                        .WithOrigins(Appsettings.App(new string[] { "Startup", "Cors", "IPs" }).Split(','))
                        .AllowAnyHeader()    //Ensures that the policy allows any header.
                        .AllowAnyMethod();
                    });
                }
                else
                {
                    //允许任意跨域请求
                    c.AddPolicy(Appsettings.App(new string[] { "Startup", "Cors", "PolicyName" }),
                                policy =>
                    {
                        policy
                        .SetIsOriginAllowed((host) => true)
                        .AllowAnyMethod()
                        .AllowAnyHeader()
                        .AllowCredentials();
                    });
                }

                //.WithOrigins(Appsettings.App(new string[] { "Startup", "Cors", "IPs" }).Split(',')) //允许部分站点跨域请求
                //.SetPreflightMaxAge(TimeSpan.FromSeconds(2520)) //添加预检请求过期时间
                //.SetIsOriginAllowed(origin => true) //允许任何域
                //.AllowAnyHeader()  //允许任何头
                //.AllowAnyMethod() //允许任何方式
                //.AllowCredentials(); // 允许Cookie信息
            });
        }
示例#26
0
        public void ConfigureContainer(ContainerBuilder builder)
        {
            var basePath = Microsoft.DotNet.PlatformAbstractions.ApplicationEnvironment.ApplicationBasePath;

            #region  Service.dll和Repository.dll注入,AOP注入
            var servicesDllFile   = Path.Combine(basePath, "MyWebApiProject.Service.dll");
            var repositoryDllFile = Path.Combine(basePath, "MyWebApiProject.Repository.dll");
            if (!(File.Exists(servicesDllFile) && File.Exists(repositoryDllFile)))
            {
                throw new Exception("Repository.dll和service.dll 丢失,因为项目解耦了,需要先F6编译,再F5运行,请检查 bin 文件夹,并拷贝。");
            }
            // AOP 开关,如果想要打开指定的功能,只需要在 appsettigns.json 对应对应 true 就行。
            var cacheType = new List <Type>();
            if (Appsettings.app(new string[] { "AppSettings", "RedisCachingAOP", "Enabled" }).ObjectToBool())
            {
                builder.RegisterType <MyApiRedisCacheAOP>();
                cacheType.Add(typeof(MyApiRedisCacheAOP));
            }
            if (Appsettings.app(new string[] { "AppSettings", "MemoryCachingAOP", "Enabled" }).ObjectToBool())
            {
                builder.RegisterType <MyApiCacheAOP>();
                cacheType.Add(typeof(MyApiCacheAOP));
            }
            if (Appsettings.app(new string[] { "AppSettings", "LogAOP", "Enabled" }).ObjectToBool())
            {
                builder.RegisterType <MyApiLogAOP>();
                cacheType.Add(typeof(MyApiLogAOP));
            }
            //获取 Service.dll 程序集服务,并注册
            var assemblyServices = Assembly.LoadFrom(servicesDllFile);
            builder.RegisterAssemblyTypes(assemblyServices)
            .AsImplementedInterfaces()
            .InstancePerDependency()
            .EnableInterfaceInterceptors()       //引用Autofac.Extras.DynamicProxy//
            .InterceptedBy(cacheType.ToArray()); //允许将拦截器服务的列表分配给注册。
                                                 //获取 Repository.dll 程序集服务,并注册
            var assemblysRepository = Assembly.LoadFrom(repositoryDllFile);
            builder.RegisterAssemblyTypes(assemblysRepository)
            .AsImplementedInterfaces()
            .InstancePerDependency();
            #endregion
        }
示例#27
0
        public static void AddNacosSetup(this IServiceCollection services, IConfiguration Configuration)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            // 在实际生产工作中 本地开发是不需要注册nacos的 所以根据环境变量去判断
            // 比如 开发环境 dev  测试环境 test  生产 prod  只有这几种环境变量的时候才需要去注册nacos
            if (Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") != null &&
                Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") != "" &&
                Appsettings.app(new string[] { "Startup", "Nacos", "Enabled" }).ObjToBool())
            {
                // 从当前配置取文件去注册naocs
                services.AddNacosV2Config(x =>
                {
                    x.ServerAddresses = JsonConfigSettings.NacosServerAddresses;
                    x.EndPoint        = "";
                    x.Namespace       = JsonConfigSettings.NacosNamespace;
                    x.DefaultTimeOut  = JsonConfigSettings.NacosDefaultTimeOut;
                    x.ListenInterval  = JsonConfigSettings.ListenInterval;
                    // swich to use http or rpc
                    x.ConfigUseRpc = false;
                });
                services.AddNacosV2Naming(x =>
                {
                    x.ServerAddresses = JsonConfigSettings.NacosServerAddresses;
                    x.EndPoint        = "";
                    x.Namespace       = JsonConfigSettings.NacosNamespace;
                    x.DefaultTimeOut  = JsonConfigSettings.NacosDefaultTimeOut;
                    x.ListenInterval  = JsonConfigSettings.ListenInterval;
                    // swich to use http or rpc
                    x.NamingUseRpc = false;
                });
                services.AddHostedService <NacosListenNamingTask>();        //增加服务注入,删除事件
                // 监听nacos中的配置中心 如果有新配置变更 执行相关逻辑
                services.AddHostedService <NacosListenConfigurationTask>(); //增加配置文件监听事件
            }

            services.AddSingleton <IConfigurationManager>(new ConfigurationManager((ConfigurationRoot)Configuration));
            services.AddSingleton(Configuration);
        }
示例#28
0
        public static void AddCorsSetup(this IServiceCollection services)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            services.AddCors(c =>
            {
                c.AddPolicy("LimitRequests", policy =>
                {
                    // 支持多个域名端口,注意端口号后不要带/斜杆:比如localhost:8000/,是错的
                    // 注意,http://127.0.0.1:1818 和 http://localhost:1818 是不一样的,尽量写两个
                    policy
                    .WithOrigins(Appsettings.app(new string[] { "Startup", "Cors", "IPs" }).Split(','))
                    .AllowAnyHeader()//Ensures that the policy allows any header.
                    .AllowAnyMethod();
                });
            });
        }
示例#29
0
        public static void UseIpLimitMildd(this IApplicationBuilder app)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }

            try
            {
                if (Appsettings.app("Middleware", "IpRateLimit", "Enabled").ObjToBool())
                {
                    app.UseIpRateLimiting();
                }
            }
            catch (Exception e)
            {
                log.Error($"Error occured limiting ip rate.\n{e.Message}");
                throw;
            }
        }
示例#30
0
        public static void UseSeedDataMildd(this IApplicationBuilder app, MyContext myContext, string webRootPath)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }

            try
            {
                if (Appsettings.app("AppSettings", "SeedDBEnabled").ObjToBool() || Appsettings.app("AppSettings", "SeedDBDataEnabled").ObjToBool())
                {
                    DBSeed.SeedAsync(myContext, webRootPath).Wait();
                }
            }
            catch (Exception e)
            {
                log.Error($"Error occured seeding the Database.\n{e.Message}");
                throw;
            }
        }