Skip to content

Instantly share code, notes, and snippets.

View ntakouris's full-sized avatar
🤖
Building robots

Theodoros Ntakouris ntakouris

🤖
Building robots
View GitHub Profile
if (executedContext.Result is OkObjectResult okObjectResult)
{
await cacheService.CacheResponseAsync(cacheKey, okObjectResult.Value, TimeSpan.FromSeconds(_timeToLiveSeconds));
}
var cacheService = context.HttpContext.RequestServices.GetRequiredService<IResponseCacheService>();
var cacheKey = GenerateCacheKeyFromRequest(context.HttpContext.Request);
var cachedResponse = await cacheService.GetCachedResponseAsync(cacheKey);
if (!string.IsNullOrEmpty(cachedResponse))
{
var contentResult = new ContentResult
{
Content = cachedResponse,
var cacheSettings = context.HttpContext.RequestServices.GetRequiredService<RedisCacheSettings>();
if (!cacheSettings.Enabled)
{
await next();
return;
}
public async Task CacheResponseAsync(string cacheKey, object response, TimeSpan timeTimeLive)
{
if (response == null)
{
return;
}
var serializedResponse = JsonConvert.SerializeObject(response);
await _distributedCache.SetStringAsync(cacheKey, serializedResponse, new DistributedCacheEntryOptions
public async Task<string> GetCachedResponseAsync(string cacheKey)
{
var cachedResponse = await _distributedCache.GetStringAsync(cacheKey);
return string.IsNullOrEmpty(cachedResponse) ? null : cachedResponse;
}
public interface IResponseCacheService
{
Task CacheResponseAsync(string cacheKey, object response, TimeSpan timeTimeLive);
Task<string> GetCachedResponseAsync(string cacheKey);
}
"RedisCacheSettings": {
"Enabled": true,
"ConnectionString": "localhost"
}
public class RedisCacheSettings
{
public bool Enabled { get; set; }
public string ConnectionString { get; set; }
}
var redisCacheSettings = new RedisCacheSettings();
configuration.GetSection(nameof(RedisCacheSettings)).Bind(redisCacheSettings);
services.AddSingleton(redisCacheSettings);
if (!redisCacheSettings.Enabled)
{
return;
}
services.AddStackExchangeRedisCache(options => options.Configuration = redisCacheSettings.ConnectionString);
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class ApiKeyAuthAttribute : Attribute, IAsyncActionFilter
{
private const string ApiKeyHeaderName = "ApiKey";
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
if (!context.HttpContext.Request.Headers.TryGetValue(ApiKeyHeaderName, out var potentialApiKey))
{
context.Result = new UnauthorizedResult();