public IActionResult Auth([FromBody] UserInfoInputDto input) { var result = _service.Login(input); if (result == null) { return(ApiResponse(null, false, "登录失败", 204)); } var claims = new[] { new Claim(JwtRegisteredClaimNames.Nbf, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"), new Claim(JwtRegisteredClaimNames.Exp, $"{new DateTimeOffset(DateTime.Now.AddDays(1)).ToUnixTimeSeconds()}"), new Claim(ClaimTypes.Name, input.username) }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(JsonConfig.GetSectionValue("Auth:SecurityKey"))); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken( issuer: JsonConfig.GetSectionValue("Auth:Domain"), audience: JsonConfig.GetSectionValue("Auth:Domain"), claims: claims, expires: DateTime.Now.AddDays(1), signingCredentials: creds); return(Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token) })); }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { var config = new ConfigurationBuilder() .SetBasePath(_env.ContentRootPath) .AddJsonFile("appsettings.json") .Build(); var builder = optionsBuilder.UseMySql(config.GetConnectionString("MYSQLConnection"), builder => { builder.EnableRetryOnFailure( maxRetryCount: 5, maxRetryDelay: TimeSpan.FromSeconds(30), null); }); var enableLog = JsonConfig.GetSectionValue("SystemConfig:EnableEfSqlLogger"); if (!string.IsNullOrWhiteSpace(enableLog) && enableLog.Equals("True")) { builder.UseLoggerFactory(_factory); } //optionsBuilder.UseSqlite(config.GetConnectionString("SQLITEConnection")); //optionsBuilder.UseSqlServer(config.GetConnectionString("MSSQLConnection")); }
public Task DoWork(IJobExecutionContext context) { lock (_lock) { var trigger = (CronTriggerImpl)((JobExecutionContextImpl)context).Trigger; try { var watch = new Stopwatch(); watch.Start(); var coin_array = JsonConfig.GetSectionValue("TradeConfig:Coin").Split(','); Parallel.ForEach(coin_array, AddKLineData); watch.Stop(); context.Scheduler.Context.Put(trigger.FullName + "_Result", "Success"); context.Scheduler.Context.Put(trigger.FullName + "_Time", watch.ElapsedMilliseconds); _logger.LogInformation($"------>{context.GetJobDetail()} 耗时:{watch.ElapsedMilliseconds} "); return(Task.FromResult("Success")); } catch (Exception ex) { context.Scheduler.Context.Put(trigger.FullName + "_Exception", ex); _logger.LogError(new EventId(ex.HResult), ex, "---CoinKLineDataJob DoWork Exception---"); return(Task.FromResult("Error")); } } }
/// <summary> /// ConfigHttps /// </summary> /// <returns></returns> private static Action <KestrelServerOptions> ConfigHttps() { return(x => { x.Listen(IPAddress.Loopback, 443, listenOptions => { var path = Directory.GetCurrentDirectory() + "\\File\\cert\\" + JsonConfig.GetSectionValue("Cert:Path"); listenOptions.UseHttps(path, JsonConfig.GetSectionValue("Cert:PassWord")); }); }); }
/// <summary> /// 获取K线 /// </summary> /// <param name="time"></param> /// <param name="size"></param> /// <returns></returns> public string GetKLine(string coin, string time, int size) { try { var http = new WebClient(); //return http.DownloadString($"https://api.huobi.pro/market/history/kline?period={time}&size={size}&symbol={coin}"); string url = $"{JsonConfig.GetSectionValue("TradeConfig:Api:Huobi")}/market/history/kline?period={time}&size={size}&symbol={coin}"; return(http.DownloadString(url)); } catch (WebException ex) { _logger.LogError(new EventId(ex.HResult), ex, $"---GetKLine {DateTime.Now}---"); throw; } }
/// <summary> /// 合约分析 /// </summary> public void Futures() { try { using var scope = _scopeFactory.CreateScope(); using var db_context = scope.ServiceProvider.GetRequiredService <CoinDbContext>(); var coin_kline_data = new Dictionary <string, List <Domain.Coin.CoinKLineData.CoinKLineData> >(); var coin_array = JsonConfig.GetSectionValue("TradeConfig:Coin").Split(','); foreach (var coin in coin_array) { foreach (CoinTime time in Enum.GetValues(typeof(CoinTime))) { var kline = db_context.CoinKLineData .Where(x => x.Coin.Equals(coin) && x.TimeType == (int)time && x.IsDelete == 0) .OrderByDescending(x => x.DataTime).Take(2000).ToList(); if (kline.Count < 1) { _logger.LogError("---K线获取失败---"); continue; } coin_kline_data.Add(coin + "_" + (int)time, kline); } } //并行计算 订单操作 Parallel.ForEach(coin_kline_data, item => { Trade(item.Key, item.Value); }); } catch (Exception ex) { _logger.LogError(new EventId(ex.HResult), ex, "---Futures Exception---"); } }
/// <summary> /// ConfigureServices /// </summary> /// <param name="services">IServiceCollection</param> public void ConfigureServices(IServiceCollection services) { services.AddMvc(options => { //全局Action Exception Result过滤器 options.Filters.Add <MvcFilter>(); }) //.AddNewtonsoftJson(options => //{ // options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss"; //}) .AddFluentValidation(config => { config.RunDefaultMvcValidationAfterFluentValidationExecutes = false; }) .ConfigureApiBehaviorOptions(config => { //关闭默认模型验证过滤器 config.SuppressModelStateInvalidFilter = true; }) .SetCompatibilityVersion(CompatibilityVersion.Version_3_0) .AddJsonOptions(options => { options.JsonSerializerOptions.Converters.Add(new DateTimeConverter()); options.JsonSerializerOptions.Converters.Add(new DateTimeNullConverter()); }); services.AddMemoryCacheEx(); //AutoMapper映射 services.AddAutoMapperSupport(); //集中注入 services.AddService(); //MemoryCache services.AddMemoryCache(); //Swagger services.AddSwagger(); //ApiVersion services.AddApiVersion(); services.AddMiniProfiler(options => { // (Optional) Path to use for profiler URLs, default is /mini-profiler-resources options.RouteBasePath = "/profiler"; // (Optional) Control which SQL formatter to use, InlineFormatter is the default options.SqlFormatter = new InlineFormatter(); // (Optional) You can disable "Connection Open()", "Connection Close()" (and async // variant) tracking. (defaults to true, and connection opening/closing is tracked) options.TrackConnectionOpenClose = true; }).AddEntityFramework(); //注入 Quartz调度类 services.AddSingleton <ISchedulerFactory, StdSchedulerFactory>(); //注册ISchedulerFactory的实例。 services.AddHealthChecksUI().AddHealthChecks().AddCheck <RandomHealthCheck>("random"); //添加jwt验证: services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, //是否验证Issuer ValidateAudience = true, //是否验证Audience ValidateLifetime = true, //是否验证失效时间 ClockSkew = TimeSpan.FromSeconds(30), ValidateIssuerSigningKey = true, //是否验证SecurityKey ValidAudience = JsonConfig.GetSectionValue("Auth:Domain"), //Audience ValidIssuer = JsonConfig.GetSectionValue("Auth:Domain"), //Issuer,这两项和前面签发jwt的设置一致 IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(JsonConfig.GetSectionValue("Auth:SecurityKey"))) //拿到SecurityKey }; }); services.AddControllers(); }