public void ConfigureServices(IServiceCollection services) { services.AddDbContext <MeuDbContext>(options => { options.UseSqlServer(ConnectionString.GetConnectionString()).UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking); }); services.AddMvc(options => { options.RespectBrowserAcceptHeader = true; }) .AddJsonOptions(op => { op.JsonSerializerOptions.IgnoreNullValues = true; }); services.AddIdentityConfiguration(Configuration); services.AddAutoMapper(typeof(Startup)); services.AddSwaggerConfig(); services.ResolveDependencies(); services.WebApiConfig(); services.ConfigureRateLimit(Configuration); //Ativa compressão dados services.AddResponseCompression(options => { options.EnableForHttps = true; options.Providers.Add <BrotliCompressionProvider>(); options.Providers.Add <GzipCompressionProvider>(); options.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(new[] { "application/json" }); }); services.Configure <GzipCompressionProviderOptions>(options => options.Level = CompressionLevel.Fastest); services.ConfigureCookie(); services.AddControllers(options => { options.Filters.Add <SerilogLoggingActionFilter>(); }) .AddJsonOptions(op => { op.JsonSerializerOptions.IgnoreNullValues = true; }); services.AddHealthChecks() .AddSqlServer(ConnectionString.GetConnectionString(), name: "Banco de Dados", tags: new[] { "db", "sql", "sqlserver" }); var datasulSeqSettings = new DatasulSeqSettings(); Configuration.GetSection("DatasulSeqSettings").Bind(datasulSeqSettings); if (datasulSeqSettings.Enabled) { services.AddHealthChecks().AddUrlGroup(new Uri(datasulSeqSettings.Url), "Datasul Seq Log"); } var cacheSettings = new RedisCacheSettings(); Configuration.GetSection("RedisCacheSettings").Bind(cacheSettings); if (cacheSettings.Enabled) { services.AddHealthChecks().AddRedis(cacheSettings.ConnectionString, "Cache Redis"); } services.Configure <HstsOptions>(options => { options.IncludeSubDomains = true; options.MaxAge = TimeSpan.FromDays(365); }); services.AddHealthChecksUI(); services.ConfigureCache(Configuration); }
public void AddRedisConfiguration(IServiceCollection services) { var redisCacheSettings = new RedisCacheSettings(); try { Configuration.GetSection(nameof(RedisCacheSettings)).Bind(redisCacheSettings); services.AddSingleton(redisCacheSettings); if (!redisCacheSettings.IsEnabled) { return; } services.AddStackExchangeRedisCache(options => options.Configuration = redisCacheSettings.ConnectionString); services.AddSingleton <IResponseCacheService, ResponseCacheService>(); // Experiment with MemoryDistributedCache //services.AddSingleton<IDistributedCache, MemoryDistributedCache>(); } catch (Exception ex) { // Log //throw; } }
public RedisCacheService(IDistributedCache distributedCache, RedisCacheSettings redisCacheSettings, ILogger <RedisCacheService> logger) { _distributedCache = distributedCache ?? throw new ArgumentNullException(nameof(distributedCache)); _redisCacheSettings = redisCacheSettings ?? throw new ArgumentNullException(nameof(redisCacheSettings)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); }
/// <summary> /// Initializes a new instance of the <see cref="RedisConnectionProvider"/> class. /// </summary> /// <param name="redisCacheSettingsAccessor">General Redis cache settings <see cref="RedisCacheSettings"/></param> /// <param name="logger">Logger <see cref="ILogger"/></param> public RedisConnectionProvider(IOptions <RedisCacheSettings> redisCacheSettingsAccessor, ILogger <RedisConnectionProvider> logger) { if (redisCacheSettingsAccessor == null) { throw new ArgumentNullException(nameof(redisCacheSettingsAccessor)); } _redisCacheSettings = redisCacheSettingsAccessor.Value; _logger = logger; IsSentinel = _redisCacheSettings.RedisUrl .Contains("serviceName=", StringComparison.InvariantCultureIgnoreCase); }
public void InstallServices(IServiceCollection services, IConfiguration configuration) { var redisCacheSettings = new RedisCacheSettings(); configuration.GetSection(nameof(RedisCacheSettings)).Bind(redisCacheSettings); services.AddSingleton(redisCacheSettings); if (redisCacheSettings.Enabled) { services.AddStackExchangeRedisCache(options => options.Configuration = redisCacheSettings.ConnectionString); services.AddSingleton <IResponseCacheService, ResponseCacheService>(); } }
//NOTE: Redis is a Cache provider public void InstallServices(IServiceCollection services, IConfiguration configuration) { var redisCacheSettings = new RedisCacheSettings(); var redisSection = configuration.GetSection(nameof(RedisCacheSettings)); redisSection.Bind(redisCacheSettings); services.AddSingleton(redisCacheSettings); services.AddStackExchangeRedisCache((options) => { options.Configuration = redisCacheSettings.ConnectionString; }); services.AddSingleton <ICacheService, CacheService>(); services.AddSingleton <IResponseCacheService, ResponseCacheService>(); }
public static IServiceCollection BootstrapCacheService(this IServiceCollection services, IConfiguration configuration) { var redisCacheSettings = new RedisCacheSettings(); configuration.GetSection(nameof(RedisCacheSettings)).Bind(redisCacheSettings); services.AddSingleton(redisCacheSettings); if (!redisCacheSettings.Enabled) { return(services); } services.AddStackExchangeRedisCache(options => options.Configuration = redisCacheSettings.ConnectionString); services.AddSingleton <IResponseCacheService, ResponseCacheService>(); return(services); }
public void InstallServices(IServiceCollection services, IConfiguration Configuration) { var redisCacheSettings = new RedisCacheSettings(); Configuration.GetSection(nameof(RedisCacheSettings)).Bind(redisCacheSettings); services.AddSingleton(redisCacheSettings); if (!redisCacheSettings.Enabled) { return; } services.AddSingleton <IConnectionMultiplexer>(_ => ConnectionMultiplexer.Connect(redisCacheSettings.ConnectionString)); services.AddDistributedRedisCache(options => options.Configuration = redisCacheSettings.ConnectionString); services.AddSingleton <IResponseCacheService, ResponseCacheService>(); }
public static IServiceCollection AddCacheServices(this IServiceCollection services, IConfiguration config) { var redisCacheSettings = new RedisCacheSettings(); config.GetSection(key: "Redis").Bind(redisCacheSettings); services.AddSingleton(redisCacheSettings); services.AddSingleton <IRedisClientsManager, RedisManagerPool>(c => new RedisManagerPool(redisCacheSettings.ConnectionString)); services.AddTransient <IRedisClient, RedisClient>(); services.AddTransient <IAccountRequestCache, AccountRequestCache>(); services.AddSingleton <IOrderBookCache, OrderBookCache>(); services.AddSingleton <IOrderCache, OrderCache>(); services.AddSingleton <IPositionCache, PositionCache>(); services.AddSingleton <IInstrumentCache, InstrumentCache>(); services.AddSingleton <IConnectionDataHandler, CacheDataHandler>(); return(services); }
private static string GetOptionsString(RedisCacheSettings settings) { var optionsStringBuilder = new StringBuilder($"{settings.RedisUrl.Trim()},abortConnect=false,allowAdmin=true"); if (settings.SyncTimeout.HasValue) { optionsStringBuilder.Append($",syncTimeout=" + settings.SyncTimeout); } if (!string.IsNullOrEmpty(settings.Password?.Trim())) { optionsStringBuilder.Append($",password=" + settings.Password.Trim()); } return(optionsStringBuilder.ToString()); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // services.AddAutoMapper(typeof(Startup)); //services.AddDbContext<PostgresqlContext>(options => // options.UseNpgsql( // _configuration.GetConnectionString("DefaultConnection"),x=>x.MigrationsAssembly("WebUI"))); services.InstallServicesInAssembly(Configuration); var tokenOptions = _configuration.GetSection("TokenOptions").Get <TokenOptions>(); services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(options => { options.SaveToken = true; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidIssuer = tokenOptions.Issuer, ValidAudience = tokenOptions.Audience, ValidateIssuerSigningKey = true, IssuerSigningKey = SecurityKeyHelper.CreateSecurityKey(tokenOptions.SecurityKey) }; }); var redisCacheSettings = new RedisCacheSettings(); _configuration.GetSection("RedisCacheSettings").Bind(redisCacheSettings); services.AddSingleton(redisCacheSettings); if (!redisCacheSettings.Enabled) { return; } services.AddStackExchangeRedisCache(options => options.Configuration = redisCacheSettings.ConnectionString); services.AddSingleton <IRedisCacheService, RedisApiCache>(); }
public static void AddCacheServices(this IServiceCollection services, IConfiguration configuration) { var redisCacheSettings = new RedisCacheSettings(); configuration.GetSection(nameof(RedisCacheSettings)).Bind(redisCacheSettings); services.AddSingleton(redisCacheSettings); if (!redisCacheSettings.Enabled) { return; } services.AddSingleton <IConnectionMultiplexer>(_ => ConnectionMultiplexer.Connect(redisCacheSettings.ConnectionString)); services.AddStackExchangeRedisCache(options => options.Configuration = redisCacheSettings.ConnectionString); services.AddSingleton <IResponseCacheService, ResponseCacheService>(); }
public void InstallServices(IServiceCollection services, IConfiguration configuration) { var redisSettings = new RedisCacheSettings(); configuration.GetSection(nameof(RedisCacheSettings)).Bind(redisSettings); services.AddSingleton(redisSettings); if (!redisSettings.Enabled) { return; } //healthcheck için service containera eklendi services.AddSingleton <IConnectionMultiplexer>(_ => ConnectionMultiplexer.Connect(redisSettings.ConnectionString)); services.AddStackExchangeRedisCache(options => options.Configuration = redisSettings.ConnectionString); services.AddSingleton <IResponseCacheService, ResponseCacheService>(); }
public void InstallServices(IServiceCollection services, IConfiguration configuration) { var redisCacheSettings = new RedisCacheSettings(); // Define the context for setup of a specific service using reflection. configuration.GetSection(nameof(RedisCacheSettings)).Bind(redisCacheSettings); services.AddSingleton(redisCacheSettings); if (!redisCacheSettings.Enabled) { return; } services.AddSingleton<IConnectionMultiplexer>(_ => ConnectionMultiplexer.Connect(redisCacheSettings.ConnectionString)); services.AddStackExchangeRedisCache(options => options.Configuration = redisCacheSettings.ConnectionString); services.AddSingleton<IResponseCacheService, ResponseCacheService>(); }
public void InstallService(IConfiguration configuration, IServiceCollection services) { var redisCacheSettings = new RedisCacheSettings(); configuration.GetSection(nameof(RedisCacheSettings)).Bind(redisCacheSettings); services.AddSingleton(redisCacheSettings); if (redisCacheSettings.Enable) { return; } //health-check services.AddSingleton <IConnectionMultiplexer>(_ => ConnectionMultiplexer.Connect(redisCacheSettings.ConnectionString)); //package: Extension.Redis, ExchangeRedis services.AddStackExchangeRedisCache(options => options.Configuration = redisCacheSettings.ConnectionString); services.AddSingleton <IResponseCacheService, ResponseCacheService>(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.RequireHttpsMetadata = false; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidIssuer = AuthOptions.ISSUER, ValidateAudience = true, ValidAudience = AuthOptions.AUDIENCE, ValidateLifetime = false, IssuerSigningKey = AuthOptions.GetSymmetricSecurityKey(), ValidateIssuerSigningKey = true, }; }); services.AddControllers(); var redisCacheSettings = new RedisCacheSettings(); Configuration.GetSection(nameof(redisCacheSettings)).Bind(redisCacheSettings); services.AddSingleton(redisCacheSettings); if (redisCacheSettings.Enabled) { services.AddStackExchangeRedisCache(options => options.Configuration = redisCacheSettings.ConnectionString); services.AddSingleton <IResponseCacheService, ResponseCacheService>(); } services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "EventApi", Version = "v1" }); var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath); }); }
public void InstallServices(IServiceCollection services, IConfiguration configuration) { var redisCacheSettings = new RedisCacheSettings(); configuration.GetSection(nameof(RedisCacheSettings)).Bind(redisCacheSettings); services.AddSingleton(redisCacheSettings); if (!redisCacheSettings.Enabled) { return; } services.AddStackExchangeRedisCache(options => options.Configuration = redisCacheSettings.RedisConnectionString); services.AddSingleton <IResponseCacheService, ResponseCacheService>(); services.AddEasyCaching(options => { options.UseRedis(redisConfig => { redisConfig.DBConfig.Endpoints.Add(new ServerEndPoint("localhost", 6379)); redisConfig.DBConfig.AllowAdmin = true; }, "redis1"); }); }
/// <summary> /// Initializes a new instance of the <see cref="CacheService"/> class /// </summary> /// <param name="redisCacheProvider">Redis connectivity settings</param> /// <param name="logger"><see cref="ILogger"/></param> /// <param name="connectionProvider">This class is used to obtain Connection Multiplexer <see cref="IConnectionProvider"/></param> /// <param name="objectConverter">This service is used to serialize objects from / to strings</param> /// <param name="scopedKeyPrefix">This prefix is used as a starting part of Redis DB keys</param> public CacheService(IOptions <RedisCacheSettings> redisCacheProvider, ILogger <CacheService> logger, IConnectionProvider connectionProvider, IObjectToTextConverter objectConverter, string scopedKeyPrefix) { if (redisCacheProvider == null) { throw new ArgumentNullException(nameof(redisCacheProvider)); } if (string.IsNullOrEmpty(scopedKeyPrefix)) { throw new ArgumentNullException(nameof(scopedKeyPrefix)); } _redisCacheSettings = redisCacheProvider.Value; _logger = logger; _connectionProvider = connectionProvider; _objectConverter = objectConverter; _projectName = scopedKeyPrefix; }
partial void DataConfigureServices(IServiceCollection services) { services.AddDbContext <DataContext>(options => { options.UseSqlServer( this.Configuration.GetConnectionString("DefaultConnection"), options => options.MigrationsHistoryTable("MigrationsHistory", "EF")); }); services .AddDefaultIdentity <User>() .AddRoles <Role>() .AddEntityFrameworkStores <DataContext>(); IdentityBuilder builder = services.AddIdentityCore <User>(opt => { opt.Password.RequireDigit = false; opt.Password.RequiredLength = 4; opt.Password.RequireNonAlphanumeric = false; opt.Password.RequireUppercase = false; }); builder = new IdentityBuilder(builder.UserType, typeof(Role), builder.Services); builder.AddEntityFrameworkStores <DataContext>(); builder.AddRoleValidator <RoleValidator <Role> >(); builder.AddRoleManager <RoleManager <Role> >(); builder.AddSignInManager <SignInManager <User> >(); var redisCasheSettings = new RedisCacheSettings(); this.Configuration.GetSection(nameof(RedisCacheSettings)).Bind(redisCasheSettings); services.AddSingleton(redisCasheSettings); if (redisCasheSettings.Enabled) { services.AddSingleton <IConnectionMultiplexer>(_ => ConnectionMultiplexer.Connect(redisCasheSettings.ConnectionString)); services.AddStackExchangeRedisCache(options => options.Configuration = redisCasheSettings.ConnectionString); services.AddSingleton <IResponseCachService, ResponseCachService>(); } }
public static IServiceCollection ConfigureCache(this IServiceCollection services, IConfiguration configuration) { var redisCacheSettings = new RedisCacheSettings(); configuration.GetSection(nameof(RedisCacheSettings)).Bind(redisCacheSettings); services.AddSingleton(redisCacheSettings); if (redisCacheSettings.Enabled) { services.AddDistributedRedisCache(option => { option.Configuration = redisCacheSettings.ConnectionString; option.InstanceName = redisCacheSettings.InstanceName; }); services.AddStackExchangeRedisCache(options => { options.Configuration = redisCacheSettings.ConnectionString; options.InstanceName = redisCacheSettings.InstanceName; }); services.AddSingleton <IResponseCacheService, ResponseCacheService>(); } return(services); }
public static void AddInjectionForSumServices(this IServiceCollection services, IConfiguration configuration) { services.AddTransient <IFileService, FileService>(); services.AddTransient <IBaseCrudService <Products, int>, ProductService>(); services.AddTransient <IProductService, ProductService>(); services.AddTransient <IBaseCrudService <Users, Guid>, UserService>(); services.AddTransient <IUserService, UserService>(); var redisSettings = new RedisCacheSettings(); configuration.Bind(nameof(redisSettings), redisSettings); services.AddSingleton(redisSettings); if (!redisSettings.Enabled) { return; } services.AddDistributedRedisCache(options => options.Configuration = redisSettings.ConnectionString); services.AddSingleton <ICacheService, CacheService>(); }
public static IServiceCollection AddDistributedCache(this IServiceCollection services, RedisCacheSettings redisCacheSettings, IHostingEnvironment environment) { if (environment.IsDevelopment()) { services.AddDistributedMemoryCache(); services.AddDataProtection() .SetApplicationName(ApplicationName); } else { services.AddDistributedRedisCache(options => { options.Configuration = $"{redisCacheSettings.RedisConnectionString},{redisCacheSettings.SessionCachingDatabase}"; }); var redis = ConnectionMultiplexer.Connect($"{redisCacheSettings.RedisConnectionString},{redisCacheSettings.DataProtectionKeysDatabase}"); services.AddDataProtection() .SetApplicationName(ApplicationName) .PersistKeysToStackExchangeRedis(redis, "DataProtection-Keys"); } return(services); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Cors configure services.AddCors(opts => { opts.AddPolicy("AllowAll", builder => { builder.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader(); //.AllowCredentials(); }); }); // Add jwt authentication services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(cfg => { cfg.RequireHttpsMetadata = false; cfg.SaveToken = true; cfg.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters() { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["AppSettings:JwtSecret"])), ValidateIssuer = true, ValidIssuer = AppSettings.Settings.Issuer, ValidateAudience = true, ValidAudience = AppSettings.Settings.Audience, RequireExpirationTime = false }; }); // DB configure services.AddDbContext <CVideoContext>(opts => opts.UseSqlServer(Configuration["ConnectionString:CVideoDB"])); services.AddScoped <CVideoContext>(); // set up redis cache var redisCacheSettings = new RedisCacheSettings(); Configuration.GetSection(nameof(RedisCacheSettings)).Bind(redisCacheSettings); services.AddSingleton(redisCacheSettings); if (redisCacheSettings.Enabled) { services.AddStackExchangeRedisCache(options => options.Configuration = redisCacheSettings.ConnectionString); services.AddSingleton <ICacheService, CacheService>(); } // get config object AppConfig.SetConfig(Configuration); // create singleton context accessor services.TryAddSingleton <IHttpContextAccessor, HttpContextAccessor>(); services.AddScoped <IGetClaimsProvider, ClaimsProvider>(); // Configure controller services.AddControllers(); // Add unit of work scope services.AddScoped <IUnitOfWork, UnitOfWork>(); // Add services AddServicesScoped(services); // Auto mapper services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); // Generate swagger services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo { Title = "CVideo API", Version = "v1" }); c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme { Description = "JWT Authorization header using the bearer scheme", Name = "Authorization", In = ParameterLocation.Header, Type = SecuritySchemeType.ApiKey }); c.AddSecurityRequirement(new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Id = "Bearer", Type = ReferenceType.SecurityScheme } }, new List <string>() } }); }); // API versioning services.AddApiVersioning(x => { x.DefaultApiVersion = new Microsoft.AspNetCore.Mvc.ApiVersion(1, 0); x.AssumeDefaultVersionWhenUnspecified = true; x.ReportApiVersions = true; }); }
public void ConfigureServices(IServiceCollection services) { // Cors configure services.AddCors(opts => { opts.AddPolicy("AllowAll", builder => { builder.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader(); //.AllowCredentials(); }); }); // configure controller services.AddControllers().AddNewtonsoftJson(option => option.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore); // add config connection string to database services.AddDbContext <ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); // add config auto mapper services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); // Add jwt authentication services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(cfg => { cfg.RequireHttpsMetadata = false; cfg.SaveToken = true; cfg.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters() { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["AppSettings:JwtSecret"])), ValidateIssuer = true, ValidIssuer = AppSettings.Settings.Issuer, ValidateAudience = true, ValidAudience = AppSettings.Settings.Audience, RequireExpirationTime = false }; }); // config redis var redisCacheSettings = new RedisCacheSettings(); Configuration.GetSection(nameof(RedisCacheSettings)).Bind(redisCacheSettings); services.AddSingleton(redisCacheSettings); if (redisCacheSettings.Enabled) { services.AddStackExchangeRedisCache(options => options.Configuration = redisCacheSettings.ConnectionString); services.AddSingleton <ICacheService, CacheService>(); } // get config object AppConfig.SetConfig(Configuration); // connect unit of work services.AddScoped <IUnitOfWork, UnitOfWork>(); //DI for all service ServiceAddScoped(services); // add config swagger services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "FPTU - Scheduling API", Version = "v1" }); c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme { Description = "JWT Authorization header using the bearer scheme", Name = "Authorization", In = ParameterLocation.Header, Type = SecuritySchemeType.ApiKey }); c.AddSecurityRequirement(new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Id = "Bearer", Type = ReferenceType.SecurityScheme } }, new List <string>() } }); }); }
public CacheService(IDistributedCache cache, RedisCacheSettings settings, JsonSerializerOptions jsonSerializerOptions) { _Cache = cache; _IsCacheEnabled = settings != null ? settings.Enabled : false; _JsonSerializerOptions = jsonSerializerOptions; }
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { var response = new MiddlewareResponse { Status = new APIResponseStatus { IsSuccessful = false, Message = new APIResponseMessage() } }; using (var scope = context.HttpContext.RequestServices.CreateScope()) { try { IServiceProvider scopedServices = scope.ServiceProvider; RedisCacheSettings redisSettings = scopedServices.GetRequiredService <RedisCacheSettings>(); if (!redisSettings.Enabled) { await next(); return; } DataContext _dataContext = scopedServices.GetRequiredService <DataContext>(); IResponseCacheService responseCacheService = scopedServices.GetRequiredService <IResponseCacheService>(); var cacheKey = Cache.GenerateCacheKeyFromRequest(context.HttpContext.Request); if (context.HttpContext.Request.Method != "GET") { await responseCacheService.ResetCacheAsync(cacheKey); } var cachedResponse = await responseCacheService.GetCacheResponseAsync(cacheKey); if (!string.IsNullOrEmpty(cachedResponse)) { var contentResult = new ContentResult { Content = cachedResponse, ContentType = "application/json", StatusCode = 200 }; context.Result = contentResult; return; } var executedContext = await next(); if (executedContext.Result is OkObjectResult okObjectResult) { await responseCacheService.CatcheResponseAsync(cacheKey, okObjectResult, TimeSpan.FromSeconds(1000)); context.HttpContext.Response.StatusCode = 200; context.Result = new OkObjectResult(okObjectResult); return; } await next(); } catch (Exception ex) { context.HttpContext.Response.StatusCode = 500; response.Status.IsSuccessful = false; response.Status.Message.FriendlyMessage = ex.Message; response.Status.Message.TechnicalMessage = ex.ToString(); context.Result = new InternalServerErrorObjectResult(response); return; } } }
public ResponseCacheService(IDistributedCache distributedCache, RedisCacheSettings _settings) { _DistributedCache = distributedCache; _Settings = _settings; }
public CacheService(IDistributedCache cache, RedisCacheSettings settings) { _Cache = cache; _IsCacheEnabled = settings != null ? settings.Enabled : false; }