/// <summary> /// 添加JwtBearer支持 /// </summary> protected virtual AuthenticationBuilder AddJwtBearer(IServiceCollection services, AuthenticationBuilder builder) { OsharpOptions option = services.GetOsharpOptions(); JwtOptions jwt = option.Jwt; if (jwt?.Enabled != true) { return(builder); } services.TryAddScoped <IJwtBearerService, JwtBearerService <TUser, TUserKey> >(); builder.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, opts => { string secret = jwt.Secret; if (secret.IsNullOrEmpty()) { throw new OsharpException("配置文件中节点OSharp:Jwt:Secret不能为空"); } opts.TokenValidationParameters = new TokenValidationParameters() { ValidIssuer = jwt.Issuer ?? "osharp identity", ValidAudience = jwt.Audience ?? "osharp client", IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret)), LifetimeValidator = (nbf, exp, token, param) => exp > DateTime.UtcNow }; opts.Events = new OsharpJwtBearerEvents(); }); return(builder); }
protected virtual AuthenticationBuilder AddCookie(IServiceCollection services, AuthenticationBuilder builder) { OsharpOptions options = services.GetOsharpOptions(); CookieOptions cookie = options.Cookie; if (cookie?.Enabled != true) { return(builder); } services.AddScoped <OsharpCookieAuthenticationEvents>(); builder.AddIdentityCookies(b => { b.ApplicationCookie.Configure(opts => { if (cookie.CookieName != null) { opts.Cookie.Name = cookie.CookieName; } opts.LoginPath = cookie.LoginPath ?? opts.LoginPath; opts.LogoutPath = cookie.LogoutPath ?? opts.LogoutPath; opts.AccessDeniedPath = cookie.AccessDeniedPath ?? opts.AccessDeniedPath; opts.ReturnUrlParameter = cookie.ReturnUrlParameter ?? opts.ReturnUrlParameter; opts.SlidingExpiration = cookie.SlidingExpiration; if (cookie.ExpireMins > 0) { opts.ExpireTimeSpan = TimeSpan.FromMinutes(cookie.ExpireMins); } opts.EventsType = typeof(OsharpCookieAuthenticationEvents); }); }); return(builder); }
/// <summary> /// 应用模块服务 /// </summary> /// <param name="provider">服务提供者</param> public override void UsePack(IServiceProvider provider) { OsharpOptions options = provider.GetOSharpOptions(); OsharpDbContextOptions contextOptions = options.GetDbContextOptions(typeof(TDbContext)); if (contextOptions?.DatabaseType != DatabaseType) { return; } using (IServiceScope scope = provider.CreateScope()) { TDbContext context = CreateDbContext(scope.ServiceProvider); if (context != null && contextOptions.AutoMigrationEnabled) { context.CheckAndMigration(); DbContextModelCache modelCache = scope.ServiceProvider.GetService <DbContextModelCache>(); modelCache?.Set(context.GetType(), context.Model); } } //种子数据 var seedDataInitializers = provider.GetServices <ISeedDataInitializer>().OrderBy(m => m.Order); foreach (ISeedDataInitializer initializer in seedDataInitializers) { initializer.Initialize(); } IsEnabled = true; }
/// <summary> /// 发送Email /// </summary> /// <param name="email">接收人Email</param> /// <param name="subject">Email标题</param> /// <param name="body">Email内容</param> /// <returns></returns> public Task SendEmailAsync(string email, string subject, string body) { OsharpOptions options = _provider.GetCommonOptions(); MailSenderOptions mailSender = options.MailSender; if (mailSender == null || mailSender.Host == null || mailSender.Host.Contains("请替换")) { throw new OsharpException("邮件发送选项不存在,请在appsetting.json配置Common.MailSender节点"); } string host = mailSender.Host, displayName = mailSender.DisplayName, userName = mailSender.UserName, password = mailSender.Password; SmtpClient client = new SmtpClient(host) { UseDefaultCredentials = false, Credentials = new NetworkCredential(userName, password) }; string fromEmail = userName.Contains("@") ? userName : "******".FormatWith(userName, client.Host.Replace("smtp.", "")); MailMessage mail = new MailMessage { From = new MailAddress(fromEmail, displayName), Subject = subject, Body = body, IsBodyHtml = true }; mail.To.Add(email); return(client.SendMailAsync(mail)); }
/// <summary> /// 将模块服务添加到依赖注入服务容器中 /// </summary> /// <param name="services">依赖注入服务容器</param> /// <returns></returns> public override IServiceCollection AddServices(IServiceCollection services) { _corsInitializer = services.GetOrAddSingletonInstance(() => (ICorsInitializer) new DefaultCorsInitializer()); _corsInitializer.AddCors(services); OsharpOptions osharp = services.GetOsharpOptions(); services.AddControllersWithViews() .AddControllersAsServices() .AddNewtonsoftJson(options => { if (osharp.Mvc?.IsLowercaseJsonProperty == false) { options.SerializerSettings.ContractResolver = new DefaultContractResolver(); } }); services.AddRouting(opts => opts.LowercaseUrls = osharp.Mvc?.IsLowercaseUrls ?? false); services.AddHttpsRedirection(opts => opts.HttpsPort = 443); services.AddScoped <UnitOfWorkImpl>(); services.AddTransient <UnitOfWorkAttribute>(); services.TryAddSingleton <IVerifyCodeService, VerifyCodeService>(); services.TryAddSingleton <IScopedServiceResolver, RequestScopedServiceResolver>(); services.Replace <ICancellationTokenProvider, HttpContextCancellationTokenProvider>(ServiceLifetime.Singleton); services.Replace <IHybridServiceScopeFactory, HttpContextServiceScopeFactory>(ServiceLifetime.Singleton); return(services); }
/// <summary> /// 生成JwtToken /// </summary> public static string CreateToken(Claim[] claims, OsharpOptions options) { JwtOptions jwtOptions = options.Jwt; string secret = jwtOptions.Secret; if (secret == null) { throw new OsharpException("创建JwtToken时Secret为空"); } SecurityKey key = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secret)); SigningCredentials credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature); DateTime now = DateTime.Now; DateTime expires = now.AddDays(7); //todo: 启用系统设置功能,在后台设置这些参数 SecurityTokenDescriptor descriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(claims), Audience = jwtOptions.Audience, Issuer = jwtOptions.Issuer, SigningCredentials = credentials, NotBefore = now, IssuedAt = now, Expires = expires }; JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler(); SecurityToken token = tokenHandler.CreateToken(descriptor); return(tokenHandler.WriteToken(token)); }
/// <summary> /// 添加OAuth2第三方登录配置 /// </summary> protected virtual AuthenticationBuilder AddOAuth2(IServiceCollection services, AuthenticationBuilder builder) { OsharpOptions osharpOptions = services.GetOsharpOptions(); IDictionary <string, OAuth2Options> dict = osharpOptions.OAuth2S; if (dict == null || dict.Count == 0) { return(builder); } foreach (var(name, options) in dict) { if (!options.Enabled) { continue; } if (string.IsNullOrEmpty(options.ClientId)) { throw new OsharpException($"配置文件中OSharp:OAuth2配置的{name}节点的ClientId不能为空"); } if (string.IsNullOrEmpty(options.ClientSecret)) { throw new OsharpException($"配置文件中OSharp:OAuth2配置的{name}节点的ClientSecret不能为空"); } switch (name) { case "QQ": builder.AddQQ(opts => { opts.AppId = options.ClientId; opts.AppKey = options.ClientSecret; }); break; case "Microsoft": builder.AddMicrosoftAccount(opts => { opts.ClientId = options.ClientId; opts.ClientSecret = options.ClientSecret; }); break; case "GitHub": builder.AddGitHub(opts => { opts.ClientId = options.ClientId; opts.ClientSecret = options.ClientSecret; }); break; } } return(builder); }
/// <summary> /// 初始化一个<see cref="PropertyUtcDateTimeConfiguration"/>类型的新实例 /// </summary> public PropertyUtcDateTimeConfiguration(IServiceProvider provider) { _entityManager = provider.GetService <IEntityManager>(); _osharpOptions = provider.GetOSharpOptions(); _dateTimeConverter = new ValueConverter <DateTime, DateTime>( local => local.ToUniversalTime(), utc => utc.ToLocalTime()); _nullableDateTimeConverter = new ValueConverter <DateTime?, DateTime?>( local => local.HasValue ? local.Value.ToUniversalTime() : local, utc => utc.HasValue ? utc.Value.ToLocalTime() : utc); }
/// <summary> /// 重写以获取SignalR服务器创建委托 /// </summary> /// <param name="services">依赖注入服务容器</param> /// <returns></returns> protected virtual Action <ISignalRServerBuilder> GetSignalRServerBuildAction(IServiceCollection services) { OsharpOptions osharp = services.GetOsharpOptions(); return(builder => builder.AddNewtonsoftJsonProtocol(options => { if (osharp.Mvc?.IsLowercaseJsonProperty == false) { options.PayloadSerializerSettings.ContractResolver = new DefaultContractResolver(); } })); }
/// <summary> /// 构建<see cref="DbContextOptionsBuilder"/>,附加必要的扩展属性 /// </summary> public static DbContextOptionsBuilder BuildDbContextOptionsBuilder <TDbContext>(this IServiceProvider provider, DbContextOptionsBuilder builder) where TDbContext : DbContext { Type dbContextType = typeof(TDbContext); OsharpOptions osharpOptions = provider.GetOSharpOptions(); OsharpDbContextOptions osharpDbContextOptions = osharpOptions?.GetDbContextOptions(dbContextType); if (osharpDbContextOptions == null) { throw new OsharpException($"无法找到数据上下文 {dbContextType.DisplayName()} 的配置信息"); } ILogger logger = provider.GetLogger(typeof(ServiceExtensions)); //启用延迟加载 if (osharpDbContextOptions.LazyLoadingProxiesEnabled) { builder = builder.UseLazyLoadingProxies(); logger.LogDebug($"数据上下文类型 {dbContextType} 应用延迟加载代理"); } DatabaseType databaseType = osharpDbContextOptions.DatabaseType; //处理数据库驱动差异处理 IDbContextOptionsBuilderDriveHandler driveHandler = provider.GetServices <IDbContextOptionsBuilderDriveHandler>() .LastOrDefault(m => m.Type == databaseType); if (driveHandler == null) { throw new OsharpException($"无法解析类型为 {databaseType} 的 {typeof(IDbContextOptionsBuilderDriveHandler).DisplayName()} 实例,是否未在Startup执行AddPack<{databaseType}DefaultDbContextMigrationPack>()"); } //选择主/从数据库连接串 IConnectionStringProvider connectionStringProvider = provider.GetRequiredService <IConnectionStringProvider>(); string connectionString = connectionStringProvider.GetConnectionString(typeof(TDbContext)); ScopedDictionary scopedDictionary = provider.GetRequiredService <ScopedDictionary>(); string key = $"DbConnection_{connectionString}"; DbConnection existingDbConnection = scopedDictionary.GetValue <DbConnection>(key); builder = driveHandler.Handle(builder, connectionString, existingDbConnection); //使用模型缓存 DbContextModelCache modelCache = provider.GetService <DbContextModelCache>(); IModel model = modelCache?.Get(dbContextType); if (model != null) { builder = builder.UseModel(model); } return(builder); }
/// <summary> /// 初始化一个<see cref="HostHttpCrypto"/>类型的新实例 /// </summary> public HostHttpCrypto(IServiceProvider provider) { _logger = provider.GetLogger(typeof(ClientHttpCrypto)); OsharpOptions options = provider.GetOSharpOptions(); if (options?.HttpEncrypt?.Enabled == true) { HttpEncryptOptions httpEncrypt = options.HttpEncrypt; _privateKey = httpEncrypt.HostPrivateKey; if (string.IsNullOrEmpty(_privateKey)) { throw new OsharpException("配置文件中HttpEncrypt节点的HostPrivateKey不能为空"); } } }
/// <summary> /// 获取实体上下文所属的数据库类型 /// </summary> public static DatabaseType GetDatabaseType(this IDbContext dbContext) { if (!(dbContext is DbContext context)) { throw new OsharpException($"参数dbContext类型为 {dbContext.GetType()} ,不能转换为 DbContext"); } OsharpOptions options = context.GetService <IOptions <OsharpOptions> >()?.Value; if (options != null) { return(options.DbContexts.First(m => m.Value.DbContextType == context.GetType()).Value.DatabaseType); } return(DatabaseType.SqlServer); }
public override bool LazyLoadingProxiesEnabled() { if (_serviceProvider == null) { IConfiguration configuration = Singleton <IConfiguration> .Instance; return(configuration["OSharp:DbContexts:Sqlite:LazyLoadingProxiesEnabled"].CastTo(false)); } OsharpOptions options = _serviceProvider.GetOSharpOptions(); OsharpDbContextOptions contextOptions = options.GetDbContextOptions(typeof(DefaultDbContext)); if (contextOptions == null) { throw new OsharpException($"上下文“{typeof(DefaultDbContext)}”的配置信息不存在"); } return(contextOptions.LazyLoadingProxiesEnabled); }
public override string GetConnectionString() { if (_serviceProvider == null) { IConfiguration configuration = Singleton <IConfiguration> .Instance; string str = configuration["OSharp:DbContexts:PostgreSql:ConnectionString"]; return(str); } OsharpOptions options = _serviceProvider.GetOSharpOptions(); OsharpDbContextOptions contextOptions = options.GetDbContextOptions(typeof(DefaultDbContext)); if (contextOptions == null) { throw new OsharpException($"上下文“{typeof(DefaultDbContext)}”的配置信息不存在"); } return(contextOptions.ConnectionString); }
/// <summary> /// 初始化一个<see cref="OsharpBuilder"/>类型的新实例 /// </summary> public OsharpBuilder(IServiceCollection services) { Services = services; _source = GetAllPacks(services); _packs = new List <OsharpPack>(); IConfiguration configuration = services.GetConfiguration(); if (configuration == null) { IConfigurationBuilder configurationBuilder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()); if (File.Exists("appsettings.json")) { configurationBuilder.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true); } if (File.Exists("appsettings.Development.json")) { configurationBuilder.AddJsonFile("appsettings.Development.json", optional: true, reloadOnChange: true); } configuration = configurationBuilder.Build(); services.AddSingleton <IConfiguration>(configuration); } if (configuration != null) { Singleton <IConfiguration> .Instance = configuration; } if (!services.AnyServiceType(typeof(ILoggerFactory))) { services.AddLogging(opts => { #if DEBUG opts.SetMinimumLevel(LogLevel.Debug); #else opts.SetMinimumLevel(LogLevel.Information); #endif }); } OsharpOptions options = new OsharpOptions(); configuration.Bind("OSharp", options); Options = options; }
/// <summary> /// 将基于Osharp数据上下文基类<see cref="DbContextBase"/>上下文类型添加到服务集合中 /// </summary> /// <typeparam name="TDbContext">基于Osharp数据上下文基类<see cref="DbContextBase"/>上下文类型</typeparam> /// <param name="services">依赖注入服务集合</param> /// <param name="optionsAction">数据库选项创建配置,将在内置配置后运行</param> /// <returns>依赖注入服务集合</returns> public static IServiceCollection AddOsharpDbContext <TDbContext>(this IServiceCollection services, Action <IServiceProvider, DbContextOptionsBuilder> optionsAction = null) where TDbContext : DbContextBase { services.AddDbContext <TDbContext>((provider, builder) => { Type dbContextType = typeof(TDbContext); OsharpOptions osharpOptions = provider.GetOSharpOptions(); OsharpDbContextOptions osharpDbContextOptions = osharpOptions?.GetDbContextOptions(dbContextType); if (osharpDbContextOptions == null) { throw new OsharpException($"无法找到数据上下文“{dbContextType.DisplayName()}”的配置信息"); } //启用延迟加载 if (osharpDbContextOptions.LazyLoadingProxiesEnabled) { builder = builder.UseLazyLoadingProxies(); } DatabaseType databaseType = osharpDbContextOptions.DatabaseType; //处理数据库驱动差异处理 IDbContextOptionsBuilderDriveHandler driveHandler = provider.GetServices <IDbContextOptionsBuilderDriveHandler>() .FirstOrDefault(m => m.Type == databaseType); if (driveHandler == null) { throw new OsharpException($"无法解析类型为“{databaseType}”的 {typeof(IDbContextOptionsBuilderDriveHandler).DisplayName()} 实例"); } ScopedDictionary scopedDictionary = provider.GetService <ScopedDictionary>(); string key = $"DnConnection_{osharpDbContextOptions.ConnectionString}"; DbConnection existingDbConnection = scopedDictionary.GetValue <DbConnection>(key); builder = driveHandler.Handle(builder, osharpDbContextOptions.ConnectionString, existingDbConnection); //使用模型缓存 DbContextModelCache modelCache = provider.GetService <DbContextModelCache>(); IModel model = modelCache?.Get(dbContextType); if (model != null) { builder = builder.UseModel(model); } //额外的选项 optionsAction?.Invoke(provider, builder); }); return(services); }
/// <summary> /// 添加名称为 OsharpPolicy 的授权策略 /// </summary> public static IServiceCollection AddFunctionAuthorizationHandler(this IServiceCollection services) { OsharpOptions options = services.GetOsharpOptions(); //services.AddAuthorization(); services.AddAuthorization(opts => { opts.AddPolicy(FunctionRequirement.OsharpPolicy, policy => { policy.Requirements.Add(new FunctionRequirement()); //policy.AuthenticationSchemes.AddIf(JwtBearerDefaults.AuthenticationScheme, options.Jwt?.Enabled == true); //policy.AuthenticationSchemes.AddIf(CookieAuthenticationDefaults.AuthenticationScheme, options.Cookie?.Enabled == true); }); }); services.AddSingleton <IAuthorizationHandler, FunctionAuthorizationHandler>(); return(services); }
/// <summary> /// 初始化一个<see cref="ClientHttpCrypto"/>类型的新实例 /// </summary> public ClientHttpCrypto(IServiceProvider provider) { _logger = provider.GetLogger(typeof(ClientHttpCrypto)); OsharpOptions options = provider.GetOSharpOptions(); if (options.HttpEncrypt?.Enabled == true) { HttpEncryptOptions httpEncrypt = options.HttpEncrypt; string clientPublicKey = httpEncrypt.ClientPublicKey; if (string.IsNullOrEmpty(clientPublicKey)) { throw new OsharpException("配置文件中HttpEncrypt节点的ClientPublicKey不能为空"); } RsaHelper rsa = new RsaHelper(); _encryptor = new TransmissionEncryptor(rsa.PrivateKey, httpEncrypt.ClientPublicKey); _publicKey = rsa.PublicKey; } }
/// <summary> /// 发送Email /// </summary> /// <param name="email">接收人Email</param> /// <param name="subject">Email标题</param> /// <param name="body">Email内容</param> /// <returns></returns> public async Task SendEmailAsync(string email, string subject, string body) { OsharpOptions options = _provider.GetOSharpOptions(); MailSenderOptions mailSender = options.MailSender; if (mailSender == null || mailSender.Host == null || mailSender.Host.Contains("请替换")) { throw new OsharpException("邮件发送选项不存在,请在appsetting.json配置OSharp:MailSender节点"); } string host = mailSender.Host, displayName = mailSender.DisplayName, userName = mailSender.UserName, password = mailSender.Password; bool enableSsl = mailSender.EnableSsl; int port = mailSender.Port; if (port == 0) { port = enableSsl ? 465 : 25; } SmtpClient client = new SmtpClient(host, port) { UseDefaultCredentials = true, EnableSsl = enableSsl, Credentials = new NetworkCredential(userName, password) }; string fromEmail = userName.Contains("@") ? userName : "******".FormatWith(userName, client.Host.Replace("smtp.", "")); MailMessage mail = new MailMessage { From = new MailAddress(fromEmail, displayName), Subject = subject, Body = body, IsBodyHtml = true }; mail.To.Add(email); await client.SendMailAsync(mail); }
private async Task <string> CreateJwtToken(User user) { //在线用户缓存 IOnlineUserCache onlineUserCache = HttpContext.RequestServices.GetService <IOnlineUserCache>(); if (onlineUserCache != null) { await onlineUserCache.GetOrRefreshAsync(user.UserName); } //生成Token,这里只包含最基本信息,其他信息从在线用户缓存中获取 Claim[] claims = { new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()), new Claim(ClaimTypes.Name, user.UserName) }; OsharpOptions options = HttpContext.RequestServices.GetService <IOptions <OsharpOptions> >().Value; string token = JwtHelper.CreateToken(claims, options); return(token); }
/// <summary> /// 应用模块服务 /// </summary> /// <param name="provider">服务提供者</param> public override void UsePack(IServiceProvider provider) { OsharpOptions options = provider.GetOSharpOptions(); OsharpDbContextOptions contextOptions = options.GetDbContextOptions(typeof(TDbContext)); if (contextOptions?.DatabaseType != DatabaseType) { return; } ILogger logger = provider.GetLogger(GetType()); using (IServiceScope scope = provider.CreateScope()) { TDbContext context = CreateDbContext(scope.ServiceProvider); if (context != null && contextOptions.AutoMigrationEnabled) { context.CheckAndMigration(logger); DbContextModelCache modelCache = scope.ServiceProvider.GetService <DbContextModelCache>(); modelCache?.Set(context.GetType(), context.Model); } } //初始化种子数据,只初始化当前上下文的种子数据 IEntityManager entityManager = provider.GetService <IEntityManager>(); Type[] entityTypes = entityManager.GetEntityRegisters(typeof(TDbContext)).Select(m => m.EntityType).Distinct().ToArray(); IEnumerable <ISeedDataInitializer> seedDataInitializers = provider.GetServices <ISeedDataInitializer>() .Where(m => entityTypes.Contains(m.EntityType)).OrderBy(m => m.Order); foreach (ISeedDataInitializer initializer in seedDataInitializers) { initializer.Initialize(); } IsEnabled = true; }
/// <summary> /// 将模块服务添加到依赖注入服务容器中 /// </summary> /// <param name="services">依赖注入服务容器</param> /// <returns></returns> public override IServiceCollection AddServices(IServiceCollection services) { OsharpOptions options = services.GetOsharpOptions(); services.TryAddScoped <IUserClaimsProvider, UserClaimsProvider <TUser, TUserKey> >(); string defaultSchema = IdentityConstants.ApplicationScheme; if (options.Jwt?.Enabled == true && options.Cookie?.Enabled != true) { defaultSchema = JwtBearerDefaults.AuthenticationScheme; } AuthenticationBuilder builder = services.AddAuthentication(opts => { opts.DefaultScheme = defaultSchema; opts.DefaultAuthenticateScheme = defaultSchema; }); AddJwtBearer(services, builder); AddCookie(services, builder); AddOAuth2(services, builder); return(services); }
/// <summary> /// 初始化一个<see cref="DefaultEmailSender"/>类型的新实例 /// </summary> public DefaultEmailSender(IServiceProvider provider) { _logger = provider.GetLogger <DefaultEmailSender>(); _options = provider.GetOSharpOptions(); }
/// <summary> /// 初始化一个<see cref="MailKitSender"/>类型的新实例 /// </summary> public MailKitSender(IServiceProvider provider) { _logger = provider.GetLogger <MailKitSender>(); _options = provider.GetOSharpOptions(); }
/// <summary> /// 将模块服务添加到依赖注入服务容器中 /// </summary> /// <param name="services">依赖注入服务容器</param> /// <returns></returns> public override IServiceCollection AddServices(IServiceCollection services) { IConfiguration configuration = services.GetConfiguration(); _osharpOptions = configuration.GetOsharpOptions(); if (_osharpOptions?.Swagger?.Enabled != true) { return(services); } services.AddMvcCore().AddApiExplorer(); services.AddSwaggerGen(options => { if (_osharpOptions?.Swagger?.Endpoints?.Count > 0) { foreach (SwaggerEndpoint endpoint in _osharpOptions.Swagger.Endpoints) { options.SwaggerDoc($"{endpoint.Version}", new OpenApiInfo() { Title = endpoint.Title, Version = endpoint.Version }); } options.DocInclusionPredicate((version, desc) => { if (!desc.TryGetMethodInfo(out MethodInfo method)) { return(false); } string[] versions = method.DeclaringType.GetAttributes <ApiExplorerSettingsAttribute>().Select(m => m.GroupName).ToArray(); if (version.ToLower() == "v1" && versions.Length == 0) { return(true); } return(versions.Any(m => m.ToString() == version)); }); } Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.xml").ToList().ForEach(file => { options.IncludeXmlComments(file); }); //权限Token options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme() { Description = "请输入带有Bearer的Token,形如 “Bearer {Token}” ", Name = "Authorization", In = ParameterLocation.Header, Type = SecuritySchemeType.ApiKey }); options.AddSecurityRequirement(new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "oauth2" } }, new[] { "readAccess", "writeAccess" } } }); options.DocumentFilter <HiddenApiFilter>(); }); return(services); }
/// <summary> /// 建立HealthChecks服务 /// </summary> /// <param name="builder">HealthChecks服务创建者</param> /// <param name="configuration">应用程序配置</param> /// <returns></returns> protected virtual IHealthChecksBuilder BuildHealthChecks(IHealthChecksBuilder builder, IConfiguration configuration) { //system long providerMemory = configuration["OSharp:HealthChecks:PrivateMemory"].CastTo(1000_000_000L); long virtualMemorySize = configuration["OSharp:HealthChecks:VirtualMemorySize"].CastTo(1000_000_000L); long workingSet = configuration["OSharp:HealthChecks:WorkingSet"].CastTo(1000_000_000L); builder.AddPrivateMemoryHealthCheck(providerMemory); //最大私有内存 builder.AddVirtualMemorySizeHealthCheck(virtualMemorySize); //最大虚拟内存 builder.AddWorkingSetHealthCheck(workingSet); //最大工作内存 OsharpOptions options = configuration.GetOsharpOptions(); //数据库 foreach (var pair in options.DbContexts.OrderBy(m => m.Value.DatabaseType)) { string connectionString = pair.Value.ConnectionString; switch (pair.Value.DatabaseType) { case DatabaseType.SqlServer: builder.AddSqlServer(connectionString, null, pair.Key); break; case DatabaseType.Sqlite: builder.AddSqlite(connectionString, name: pair.Key); break; case DatabaseType.MySql: builder.AddMySql(connectionString, pair.Key); break; case DatabaseType.PostgreSql: builder.AddNpgSql(connectionString, name: pair.Key); break; case DatabaseType.Oracle: builder.AddOracle(connectionString, name: pair.Key); break; default: throw new ArgumentOutOfRangeException($"OSharpOptions中 {pair.Value.DatabaseType} 不受支持"); } } //SMTP if (options.MailSender != null) { var smtp = options.MailSender; builder.AddSmtpHealthCheck(smtpOptions => { smtpOptions.Host = smtp.Host; smtpOptions.LoginWith(smtp.UserName, smtp.Password); }); } //Redis if (options.Redis != null && options.Redis.Enabled) { var redis = options.Redis; builder.AddRedis(redis.Configuration); } //Hangfire if (configuration["OSharp:Hangfire:Enabled"].CastTo(false)) { builder.AddHangfire(hangfireOptions => { hangfireOptions.MinimumAvailableServers = 1; }); } return(builder); }