Пример #1
0
 public static async Task StartupAsync()
 {
     try
     {
         Server _server = new Server
         {
             Services = { QuartzServices.BindService(new QuartzJobService()) },
             Ports    = { new ServerPort("localhost", 40001, ServerCredentials.Insecure) }
         };
         _server.Start();
         var Db       = DBClientManage.GetSqlSugarClient();
         var schedule = Db.Queryable <ScheduleEntity>().Where(w => w.RunStatus == JobRunStatus.run).ToList();
         foreach (var item in schedule)
         {
             if (!string.IsNullOrEmpty(item.AssemblyName) && !string.IsNullOrEmpty(item.ClassName))
             {
                 await SchedulerCenter.GetSchedulerCenter().RunScheduleJob(item);
             }
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex);
     }
 }
Пример #2
0
        public static async Task SeedAsync()
        {
            ISqlSugarClient sugarClient = DBClientManage.GetSqlSugarClient(InitKeyType.Attribute);

            // 创建数据库
            sugarClient.DbMaintenance.CreateDatabase();
            //反射创建表 只需继承RootEntity即可
            typeof(RootEntity).Assembly.GetTypes()
            .Where(i => i.BaseType == typeof(RootEntity))
            .ToList().ForEach(item =>
            {
                // 创建表
                sugarClient.CodeFirst.InitTables(item);
            });
            await Task.FromResult("");
        }
        public override async Task <QuartzNetResult> RunScheduleJob(ScheduleModel schedule, ServerCallContext context)
        {
            var result = new QuartzNetResult()
            {
                Code = -1, Msg = "ʧ°Ü"
            };
            var Db       = DBClientManage.GetSqlSugarClient();
            var Schedule = await Db.Queryable <ScheduleEntity>().FirstAsync(w => w.Id == schedule.JonId);

            if (Schedule != null)
            {
                BaseQuartzNetResult baseQuartz = await SchedulerCenter.GetSchedulerCenter().RunScheduleJob(Schedule);

                result.Code = baseQuartz.Code;
                result.Msg  = baseQuartz.Msg;
            }
            return(result);
        }
Пример #4
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //services.AddGrpc();
            services.AddSingleton(new Appsettings());
            services.AddScoped <ICache, MemoryCaching>();
            services.AddScoped <IUser, AspNetUser>();
            services.AddSingleton <TemplateConfig>();
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddSingleton <IMemoryCache>(factory =>
            {
                var cache = new MemoryCache(new MemoryCacheOptions());
                return(cache);
            });
            services.AddScoped <SqlSugar.ISqlSugarClient>(p => DBClientManage.GetSqlSugarClient());
            services.AddSingleton <QuartzServicesClient>(p =>
            {
                Channel _channel = new Channel(Appsettings.app(new string[] { "AppSettings", "gRPCClient", "ConnectionString" }), ChannelCredentials.Insecure);
                return(new QuartzServicesClient(_channel));
            });
            services.AddSignalR();
            services.AddScoped <ICodeContext, CodeContext>();
            services.AddAutoMapperSetup();
            services.AddWebSocketManager();
            services.AddQuartzManager();
            var jwtSetting = ServerJwtSetting.GetJwtSetting();

            // 角色与接口的权限要求参数
            var permissionRequirement = new PermissionRequirement(
                "/api/error",                             // 拒绝授权的跳转地址(目前无用)
                new List <PermissionItemView>(),
                ClaimTypes.Role,                          //基于角色的授权
                jwtSetting.Issuer,                        //发行人
                jwtSetting.Audience,                      //听众
                jwtSetting.Credentials,                   //签名凭据
                expiration: TimeSpan.FromSeconds(60 * 60) //接口的过期时间
                );

            services.AddAuthorization(options =>
            {
                options.AddPolicy("public", policy => policy.RequireRole("public").Build());
            });
            // 3、复杂的策略授权
            services.AddAuthorization(options =>
            {
                options.AddPolicy(Permissions.Name,
                                  policy => policy.Requirements.Add(permissionRequirement));
            });

            // 注入权限处理器
            services.AddScoped <IAuthorizationHandler, PermissionHandler>();
            services.AddSingleton(permissionRequirement);

            services.AddAuthentication(o =>
            {
                o.DefaultScheme          = JwtBearerDefaults.AuthenticationScheme;
                o.DefaultChallengeScheme = nameof(ApiResponseHandler);
                o.DefaultForbidScheme    = nameof(ApiResponseHandler);
            })
            .AddJwtBearer(options =>
            {
                options.Events = new JwtBearerEvents()
                {
                    OnAuthenticationFailed = context =>
                    {
                        // 如果过期,则把<是否过期>添加到,返回头信息中
                        if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
                        {
                            context.Response.Headers.Add("Token-Expired", "true");
                        }
                        return(Task.CompletedTask);
                    }
                };

                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidIssuer      = jwtSetting.Issuer,
                    ValidAudience    = jwtSetting.Audience,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSetting.SecurityKey)),
                    ClockSkew        = TimeSpan.Zero
                };
            })
            .AddScheme <AuthenticationSchemeOptions, ApiResponseHandler>(nameof(ApiResponseHandler), o => { });

            services.AddSwaggerGen(option =>
            {
                option.SwaggerDoc("BlogVue", new OpenApiInfo
                {
                    Version     = "v1",
                    Title       = "Framework.Core API",
                    Description = "API for Framework.Core",
                });
                // 开启加权小锁
                option.OperationFilter <AddResponseHeadersFilter>();
                option.OperationFilter <AppendAuthorizeToSummaryOperationFilter>();

                // 在header中添加token,传递到后台
                option.OperationFilter <SecurityRequirementsOperationFilter>();

                // 必须是 oauth2
                option.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
                {
                    Description = "JWT授权在下框中输入 Bearer Token值(注意两者之间是一个空格)",
                    Name        = "Authorization",          //jwt默认的参数名称
                    In          = ParameterLocation.Header, //jwt默认存放Authorization信息的位置(请求头中)
                    Type        = SecuritySchemeType.ApiKey
                });
                //// 配置apixml名称
                option.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, $"{typeof(Startup).Assembly.GetName().Name}.xml"), true);
            });

            services.AddControllers(o =>
            {
                // 全局异常过滤
                //o.Filters.Add(typeof(GlobalExceptionsFilter));
            });
            //去除Json序列化DateTime类型 T字符
            services.AddControllers().AddJsonOptions(configure =>
            {
                configure.JsonSerializerOptions.Converters.Add(new DatetimeJsonConverter());
            });
            //DBStartup.SeedAsync().Wait();
        }