public RedisCache() { _configration = AppsettingsHelper.Get(new string[] { "AppSettings", "RedisCaching", "ConnectionString" }); if (string.IsNullOrEmpty(_configration)) { throw new ArgumentException("redis config is empty", nameof(_configration)); } }
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { //��ӿ��������� services.AddControllers(); //�����չ�������������������Ĭ�ϵ�swagger���� //swagger���� AspNetCoreExtensionsConfig.SwaggerDocOptions = AppsettingsHelper.GetSection <SwaggerDocOptions>("SwaggerDocOptions"); services.AddAspNetCoreExtensions(); }
/// <summary> /// 初始化 需要处理数据的信息 /// </summary> /// <param name="alarmService"></param> /// <param name="meterageService"></param> public OaAlarmModule(IAlarmService alarmService, IMeterageService meterageService) { _clientInfo = CallContext.GetData <ClientInfo>("clientInfo"); _dataOaQueue = RedisHelper.Get <DataOaQueue>(_clientInfo.Database); if (_dataOaQueue == null) { _dataOaQueue = new DataOaQueue(); } _alarmCount = Convert.ToInt32(AppsettingsHelper.GetConfigString("AlarmCount")); _alarmService = alarmService; _meterageService = meterageService; }
/// <summary> /// 构造函数 /// </summary> protected BaseRepository() { ClientInfo clientInfo = CallContext.GetData <ClientInfo>("clientInfo"); string ip = AppsettingsHelper.GetConfigString("DataBase", "Ip"); string account = AppsettingsHelper.GetConfigString("DataBase", "Account"); string password = AppsettingsHelper.GetConfigString("DataBase", "Password"); string connectionStr = $"Database='{clientInfo.Database}';Data Source='{ip}';User Id='{account}';Password='******';"; //string connectionStr = AppsettingsHelper.GetConfigString("DataBase", "ConnectionString"); DbContext.Init(connectionStr); Db = DbContext.GetContext().Db; DbEntity = new SimpleClient <TEntity>(Db); }
/// <summary> /// 颁发JWT字符串 /// </summary> /// <param name="tokenModel"></param> /// <returns></returns> public static string IssueJwt(JwtTokenModel tokenModel) { string iss = AppsettingsHelper.App(new string[] { "Audience", "Issuer" }); string aud = AppsettingsHelper.App(new string[] { "Audience", "Audience" }); string secret = AppsettingsHelper.App(new string[] { "Audience", "Secret" }); var claims = new List <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()}"), new Claim(JwtRegisteredClaimNames.Exp, $"{new DateTimeOffset(DateTime.Now.AddSeconds(1000)).ToUnixTimeSeconds()}"), new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(1000).ToString()), 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); }
public static void AddAuthorizationExtension(this IServiceCollection services) { if (services == null) { throw new ArgumentNullException(nameof(services)); } // ①権限付与 // 使用例:[Authorize(Policy = "Admin")] services.AddAuthorization(options => { options.AddPolicy("User", policy => policy.RequireRole("User").Build()); options.AddPolicy("SystemOrAdmin", policy => policy.RequireRole("Admin", "System")); }); // 設定ファイルの読み込み var symmetricKeyAsBase64 = AppsettingsHelper.app(new string[] { "AppSettings", "JwtSetting", "SecretKey" }); var keyByteArray = Encoding.ASCII.GetBytes(symmetricKeyAsBase64); var signingKey = new SymmetricSecurityKey(keyByteArray); var Issuer = AppsettingsHelper.app(new string[] { "AppSettings", "JwtSetting", "Issuer" }); var Audience = AppsettingsHelper.app(new string[] { "AppSettings", "JwtSetting", "Audience" }); // トークン査証パラメータ var tokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = signingKey, ValidateIssuer = true, ValidIssuer = Issuer, //発行者 ValidateAudience = true, ValidAudience = Audience, //受取者 ValidateLifetime = true, ClockSkew = TimeSpan.FromSeconds(30), RequireExpirationTime = true, }; // ②認証:.Net Core自身のJWT認証 // Bearer認証起動 services.AddAuthentication(o => { o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; o.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) // JwtBearerサービス .AddJwtBearer(o => { o.TokenValidationParameters = tokenValidationParameters; o.Events = new JwtBearerEvents { OnAuthenticationFailed = context => { // トークン期限が切れた場合、ヘッダーに関連情報を設定 if (context.Exception.GetType() == typeof(SecurityTokenExpiredException)) { context.Response.Headers.Add("Token-Expired", "true"); } return(Task.CompletedTask); } }; }); }
public void SendTextMessage1() { var aa = AppsettingsHelper.GetValue("DingTalkWebhook"); }
/// <summary> /// 将服务添加到容器 /// </summary> /// <param name="services"></param> public IServiceProvider ConfigureServices(IServiceCollection services) { #region 部分服务注入-netcore自带方法 //缓存注入 services.AddSingleton <IMemoryCache>(factory => new MemoryCache(new MemoryCacheOptions())); //redis services.AddSingleton <IRedisCache, RedisCache>(); //log日志注入 services.AddSingleton <ILoggerHelper, LogHelper>(); #endregion #region 初始化DB //services.AddScoped<DbContext>(); #endregion #region CORS services.AddCors(c => { ////↓↓↓↓↓↓↓注意正式环境不要使用这种全开放的处理↓↓↓↓↓↓↓↓↓↓ //c.AddPolicy("AllRequests", policy => //{ // policy // .AllowAnyOrigin()//允许任何源 // .AllowAnyMethod()//允许任何方式 // .AllowAnyHeader()//允许任何头 // .AllowCredentials();//允许cookie //}); ////↑↑↑↑↑↑↑注意正式环境不要使用这种全开放的处理↑↑↑↑↑↑↑↑↑↑ //一般采用这种方法 c.AddPolicy("LimitRequests", policy => { policy .WithOrigins("http://*****:*****@iwenli.org", Url = "http://www.iwenli.org" } }); c.OrderActionsBy(m => m.RelativePath); }); #region 读取xml信息 var xmlPath = Path.Combine(basePath, "Demo.Core.xml"); //这个就是刚刚配置的xml文件名 c.IncludeXmlComments(xmlPath, true); //默认的第二个参数是false,这个是controller的注释,记得修改 var xmlModelPath = Path.Combine(basePath, "Demo.Core.Model.xml"); //这个就是Model层的xml文件名 c.IncludeXmlComments(xmlModelPath); #endregion #region Token绑定到ConfigureServices //添加header验证信息 //c.OperationFilter<SwaggerHeader>(); var issuerName = (Configuration.GetSection("Audience"))["Issuer"]; var security = new Dictionary <string, IEnumerable <string> > { { issuerName, new string[] { } }, }; c.AddSecurityRequirement(security); c.AddSecurityDefinition(issuerName, new ApiKeyScheme { Description = "JWT授权(数据将在请求头中进行传输) 直接在下框中输入Bearer {token}(注意两者之间是一个空格)\"", Name = "Authorization", //jwt默认的参数名称 In = "header", //jwt默认存放Authorization信息的位置(请求头中) Type = "apiKey" }); #endregion }); #endregion #region MVC + 注入全局异常捕获 services.AddMvc(m => { //全局异常过滤 m.Filters.Add(typeof(GlobalExceptionsFilter)); }) .SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Version_2_2) //全局配置Json序列化处理 .AddJsonOptions(options => { //忽略循环引用 options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; //不使用驼峰样式的key //options.SerializerSettings.ContractResolver = new DefaultContractResolver(); //设置时间格式 options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss"; }); #endregion #region Token服务注册 services.AddSingleton((Func <IServiceProvider, IMemoryCache>)(factory => { var cache = new Microsoft.Extensions.Caching.Memory.MemoryCache(new MemoryCacheOptions()); return(cache); })); services.AddAuthorization(options => { options.AddPolicy("Client", policy => policy.RequireRole("Client").Build()); options.AddPolicy("Admin", policy => policy.RequireRole("Admin").Build()); options.AddPolicy("AdminOrClient", policy => policy.RequireRole("Admin,Client").Build()); }); #endregion #region AutoFac //实例化 AutoFac 容器 var builder = new ContainerBuilder(); //注册要通过反射创建的组件 builder.RegisterType <LogAop>(); builder.RegisterType <MemoryCacheAop>(); builder.RegisterType <RedisCacheAop>(); //builder.RegisterType<AdvertisementServices>().As<IAdvertisementServices>(); try { #region 引用项目,通过FileLoad var serviceDllFile = Path.Combine(basePath, "Demo.Core.Service.dll"); var serviceAssembly = Assembly.LoadFile(serviceDllFile); // AOP 开关,如果想要打开指定的功能,只需要在 appsettigns.json 对应对应 true 就行。 var cacheType = new List <Type>(); if (AppsettingsHelper.Get(new string[] { "AppSettings", "RedisCaching", "Enabled" }).ObjToBool()) { cacheType.Add(typeof(RedisCacheAop)); } if (AppsettingsHelper.Get(new string[] { "AppSettings", "MemoryCachingAop", "Enabled" }).ObjToBool()) { cacheType.Add(typeof(MemoryCacheAop)); } if (AppsettingsHelper.Get(new string[] { "AppSettings", "LogAop", "Enabled" }).ObjToBool()) { cacheType.Add(typeof(LogAop)); } builder.RegisterAssemblyTypes(serviceAssembly) .AsImplementedInterfaces() .InstancePerLifetimeScope() .EnableInterfaceInterceptors() //引用Autofac.Extras.DynamicProxy; //如果你想注入两个,就这么写 InterceptedBy(typeof(BlogCacheAOP), typeof(BlogLogAOP)); //如果想使用Redis缓存,请必须开启 redis 服务,端口号我的是6319,如果不一样还是无效,否则请使用memory缓存 BlogCacheAOP .InterceptedBy(cacheType.ToArray()) //允许将拦截器服务的列表分配给注册。 ; var repositoryDllFile = Path.Combine(basePath, "Demo.Core.Repository.dll"); var repositoryAssembly = Assembly.LoadFile(repositoryDllFile); builder.RegisterAssemblyTypes(repositoryAssembly).AsImplementedInterfaces(); #endregion #region 直接引用项目 //var servicveAssembly = Assembly.Load("Demo.Core.Service"); //builder.RegisterAssemblyTypes(servicveAssembly).AsImplementedInterfaces(); //指定已扫描程序集中的类型注册为提供所有其实现的接口。 //var repositoryAssembly = Assembly.Load("Demo.Core.Repository"); //builder.RegisterAssemblyTypes(repositoryAssembly).AsImplementedInterfaces(); #endregion #endregion } catch (Exception e) { throw new Exception(e.Message); } //将 services 填充 AutoFac 容器生成器 builder.Populate(services); //使用已进行的组件等级创建新容器 var applicationContainer = builder.Build(); //第三方ico接管 return(new AutofacServiceProvider(applicationContainer)); }
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddControllers(); AspNetCoreExtensionsConfig.SwaggerDocOptions = AppsettingsHelper.GetSection <SwaggerDocOptions>("SwaggerDocOptions"); services.AddAspNetCoreExtensions(); }
static void Main(string[] args) { var basePath = Environment.CurrentDirectory; string redisIP = AppsettingsHelper.GetConfigString("RedisConfig", "IP"); string redisPassword = AppsettingsHelper.GetConfigString("RedisConfig", "Password"); LoggerRepository = LogManager.CreateRepository("BPDM.Logger"); XmlConfigurator.Configure(LoggerRepository, new FileInfo("Log4net.config")); RedisHelper.Initialization(new CSRedis.CSRedisClient($"{redisIP},password={redisPassword},defaultDatabase=13,poolsize=50,ssl=false,writeBuffer=10240,prefix=key前辍")); IServiceCollection services = new ServiceCollection(); services.AddAutoMapper(); services.AddTransient <IHandshakeModule, HandshakeModule>(); services.AddTransient <ISiteModule, SiteModule>(); services.AddTransient <IDataOaModule, DataOaModule>(); services.AddTransient <IDataTwModule, DataTwModule>(); services.AddTransient <IExtractModule, ExtractModule>(); services.AddTransient <IConfigModule, ConfigModule>(); services.AddTransient <IOaAlarmModule, OaAlarmModule>(); services.AddSingleton <ILoggerHelper, LogHelper>(); services.AddTransient <IStopModule, StopModule>(); ContainerBuilder builder = new ContainerBuilder(); var servicesDllFile = Path.Combine(basePath, "Vs.Service.dll"); var assemblysServices = Assembly.LoadFile(servicesDllFile); builder.RegisterAssemblyTypes(assemblysServices) .AsImplementedInterfaces() .InstancePerDependency(); var repositoryDllFile = Path.Combine(basePath, "Vs.Repository.dll"); var assemblysRepository = Assembly.LoadFile(repositoryDllFile); builder.RegisterAssemblyTypes(assemblysRepository).AsImplementedInterfaces().InstancePerDependency(); builder.Populate(services); container = builder.Build(); LoggerHelper = container.Resolve <ILoggerHelper>(); Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); using (StreamReader sr = new StreamReader(Path.Combine(basePath, "clientInfo.json"), Encoding.GetEncoding("gb2312"))) { string json = sr.ReadToEnd(); ClientInfoList = JsonConvert.DeserializeObject <List <ClientInfo> >(json); } string address = AppsettingsHelper.GetConfigString("SocketServer", "Address"); int port = Convert.ToInt32(AppsettingsHelper.GetConfigString("SocketServer", "port")); IPAddress ip = IPAddress.Parse(address); Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //绑定IP地址:端口 serverSocket.Bind(new IPEndPoint(ip, port)); //设定最多10个排队连接请求 serverSocket.Listen(10); //线程池的容量过去设置 int workerThreads_max = 0; int completionPortThreads_max = 0; int workerThreads_min = 0; int completionPortThreads_min = 0; //获取当前系统最大、最小线程池容量 ThreadPool.GetMaxThreads(out workerThreads_max, out completionPortThreads_max); ThreadPool.GetMinThreads(out workerThreads_min, out completionPortThreads_min); //自定义线程池容量 workerThreads_max = 12; // 12; completionPortThreads_max = 12; //12; workerThreads_min = 5; // 5; completionPortThreads_min = 5; // 5; ThreadPool.SetMinThreads(workerThreads_min, completionPortThreads_min); // set min thread to 5 ThreadPool.SetMaxThreads(workerThreads_max, completionPortThreads_max); // set max thread to 12 ThreadPool.QueueUserWorkItem(SendEmail); //启动发送邮件 while (true) { try { Socket clientSocket = serverSocket.Accept(); Console.WriteLine($"{clientSocket.RemoteEndPoint}连接成功!时间:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}"); SocketMiddleware socket = new SocketMiddleware(clientSocket); ThreadPool.QueueUserWorkItem(ExcuteAnalyse, socket); } catch (Exception e) { LoggerHelper.Error(typeof(Program), e.Message, e); Console.WriteLine(e); } } }