首页 > 解决方案 > 尝试将 StackExchange.Redis 中的 .HashSet 用于 .NET 并获得“空值在此上下文中无效”。

问题描述

我有一个从数据库返回值以动态填充页脚的 api。这些页脚值作为键存储在端点的 Redis 中,然后在主应用程序中,我获取当前页面的 url 并创建一个哈希,键为当前 url,从 api 返回的 5 个 redis 键/值作为哈希条目。我在下面显示了代码,在HashSet所在的位置(最后)是错误开始的位置,但是如果我删除了cache.Hashset,代码运行良好。我需要预先填充哈希还是我在这里遗漏了一些明显的东西?

//Get relative url after .com/
                var url = HttpContext.Current.Request.Url.ToString();
                var urlSplit = url.Split(new string[] { ".com/" }, StringSplitOptions.None);
                var finalUrl = urlSplit[1];

                //TODO: If url isn't in Redis, want to hit endpoint and load it into Redis
                //in the background with worker service/async call.
                var cache = RedisHelper.Connection.GetDatabase();
                var hashExists = cache.HashExists(finalUrl, "footer:recent-content");

                if (hashExists)
                {
                     recentContent = cache.HashGet(finalUrl, "footer:recent-content");
                     topPages = cache.HashGet(finalUrl, "footer:top-pages");
                     featuredContent = cache.HashGet(finalUrl, "footer:featured-content");
                     topIntegrations = cache.HashGet(finalUrl, "footer:top-integrations");
                     featuredIntegrations = cache.HashGet(finalUrl, "footer:featured-integrations");

                }
                else
                {
                    recentContent = cache.StringGet("footer:general:recent-content");
                    topPages = cache.StringGet("footer:general:top-pages");
                    featuredContent = cache.StringGet("footer:general:featured-content");
                    topIntegrations = cache.StringGet("footer:general:top-integrations");
                    featuredIntegrations = cache.StringGet("footer:general:featured-integrations");

                    HashEntry[] redisFooterHash = 
                        {
                        new HashEntry("footer:recent-content", recentContent),
                        new HashEntry("footer:top-pages", topPages),
                        new HashEntry("footer:featured-content", featuredContent),
                        new HashEntry("footer:top-integrations", topIntegrations),
                        new HashEntry("footer:featured-integrations", featuredIntegrations)
                        };

                    cache.HashSet(finalUrl, redisFooterHash);
                   }

此外,键是 footer:recent-content 和 footer:general... 的原因是将来我们希望每个页面都有一个基于其内容的动态页脚。

标签: c#asp.netredisstackexchange.redis

解决方案


推荐阅读