I'm trying to connect to an Azure Cache For Redis. I'm using .net 6 and I use StackExchangeRedis to cache a response, it works in localhost but in deployment is not working, please help me .... I also find an answer in many Forum but ain't work
My code config for Redis
application.json
"RedisCacheSetting": {
"Enabled": true,
"ConnectionString": "tutor-helper.redis.cache.windows.net:6380,password=*****PuCERKKnrcbff0y3hWpZ***m1BaY40=,ssl=True,abortConnect=False"
},
Cache Attribute
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class CachedAttribute : Attribute, IAsyncActionFilter
{
private readonly int _timeToLiveSeconds;
public CachedAttribute(int timeToLiveSeconds)
{
_timeToLiveSeconds = timeToLiveSeconds;
}
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
var cacheSetting = context.HttpContext.RequestServices.GetRequiredService<RedisCacheSetting>();
if (!cacheSetting.Enabled)
{
await next();
return;
}
var cacheService = context.HttpContext.RequestServices.GetRequiredService<IResponseCacheService>();
var cacheKey = GenerateKeyFromRequest(context.HttpContext.Request);
var cacheResponse = await cacheService.GetCacheResponseAsync(cacheKey);
if (!string.IsNullOrEmpty(cacheResponse))
{
var rs = new ContentResult
{
Content = cacheResponse,
ContentType = "application/json",
StatusCode = 200,
};
context.Result = rs;
return;
}
var executedContext = await next();
if (executedContext.Result is ObjectResult okObjectResult)
{
await cacheService.CacheResponseAsync(cacheKey, okObjectResult.Value, TimeSpan.FromSeconds(_timeToLiveSeconds));
}
}
private static string GenerateKeyFromRequest(HttpRequest request)
{
var keyBuilder = new StringBuilder();
keyBuilder.Append($"{request.Path}");
foreach (var (key, value) in request.Query.OrderBy(x => x.Key))
{
keyBuilder.Append($"|{key}-{value}");
}
return keyBuilder.ToString();
}
}
Config in startup.cs
public static void SetUpCache(this IServiceCollection services, IConfiguration configuration)
{
var redisCache = new RedisCacheSetting();
configuration.GetSection(nameof(RedisCacheSetting)).Bind(redisCache);
services.AddSingleton(redisCache);
//services.Configure<RedisCacheSetting>(configuration.GetSection("RedisCacheSetting"));
//services.AddDistributedRedisCache(op => op.Configuration = redisCache.ConnectionString);
services.AddStackExchangeRedisCache(op => op.Configuration = redisCache.ConnectionString);
services.AddSingleton<IResponseCacheService, ResponseCacheService>();
}