c# - ASP.NET Core 2.1 - 内存缓存 - 控制器无法访问中间件中设置的值
问题描述
我在 Asp.Net Core 2.1 Webapi 项目中使用 IMemoryCache 来临时存储从 RabbitMq 通道接收到的一些数据。我在定制的中间件中有一个频道监听器。但是当我尝试从控制器访问缓存中的数据时,里面没有数据。我使用 Autofac 作为我的 DI 框架。
如果我在控制器中为内存缓存设置一个值,我可以从其他类中获取它,例如与此控制器关联的服务(也在 Autofac DI 中注册)。
我的实现如下:
- 在 Startup.cs 中,我有
services.AddMemoryCache();
然后使用中间件作为
app.UseMiddleware<RabbitMqConsumerMiddleware>();
app.UseCors("default")
.UseAuthentication()
.UseMvc();`
我的 Autofac 注册如下:
这是我的 Autofac 注册
public IServiceProvider ConfigureServices(IServiceCollection services)
{
RabbitMqConfiguration rabbitMqConfiguration = new RabbitMqConfiguration();
Configuration.GetSection("RabbitMq").Bind(rabbitMqConfiguration);
services.AddSingleton(rabbitMqConfiguration);
services.AddMvcCore()
.AddAuthorization()
.AddJsonFormatters()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
.AddDataAnnotationsLocalization()
.AddControllersAsServices()
.AddApiExplorer();
services.AddRabbitMq(rabbitMqConfiguration);
services.AddMemoryCache();
ContainerBuilder builder = new ContainerBuilder();
builder.Populate(services);
IContainer container = builder.Build();
return new AutofacServiceProvider(container);
}
在中间件中,我有
public RabbitMqConsumerMiddleware(RequestDelegate next, IMemoryCache memoryCache, RabbitMqConfiguration configuration, IModel messageBodyReceiverChannel) { _next = next; _memoryCache = memoryCache; _configuration = configuration; _messageBodyReceiverChannel = messageBodyReceiverChannel; } public async Task Invoke(HttpContext context) { bool isMessageBodyReceiverConsumerExist = _memoryCache.TryGetValue("message-body-receiver-consumer", out EventingBasicConsumer messageBodyReceiverConsumer); if (!isMessageBodyReceiverConsumerExist) { var messageBodyReceiverConsumer = new EventingBasicConsumer(_messageBodyReceiverChannel); messageBodyReceiverConsumer.Received += (ch, ea) => { MessageBody messageBody = JsonConvert.DeserializeObject<MessageBody>(Encoding.Default.GetString(ea.Body)); if (_memoryCache.TryGetValue("Message Body", out List<MessageBody> cacheMessageBodies)) { cacheMessageBodies.Add(messageBody); } else { _memoryCache.Set("Message Body", new List<MessageBody> { messageBody }); } }; _memoryCache.Set("message-body-receiver-consumer", messageBodyReceiverConsumer); } _messageBodyReceiverChannel.BasicConsume(_configuration.MessageReceiverQueue, false, messageBodyReceiverConsumer); await _next(context); }
RabbitMqmessageBody
来自哪里
在控制器中我有
[Authorize] [Route("[controller]")] [ApiController] public class MessageBodyController : ControllerBase { private readonly IApplicationService<Dto.MessageBody> _messageBodyPresenter; private readonly IMemoryCache _memoryCache; public MessageBodyController(IApplicationService<Dto.MessageBody> messageBodyPresenter, IMemoryCache memoryCache) { _messageBodyPresenter = messageBodyPresenter; _memoryCache = memoryCache; } [HttpGet] [Route("Stop")] public IActionResult Stop() { ((MessageBodyPresenter)_messageBodyPresenter).Stop(); return Ok(); } }
但_memoryCache
总是空的。
我在中间件中放了一个断点,并确认数据已设置到缓存中。
我是否以错误的方式使用内存缓存?谢谢
解决方案
在不知道您的完整配置的情况下,我想一个问题可能是您在 Mvc 中间件之后注册了新的中间件。
您的注册应如下所示:
app.UseMiddleware<RabbitMqConsumerMiddleware>();
app.UseMvc();
推荐阅读
- javascript - 滚动间谍在引导程序 4 中没有响应
- c# - 使用 LINQ 提取 JSON 属性
- service - 统一 Kubernetes 中的服务端点
- node.js - 纱线启动和 ExecCommand.execute 出错
- aws-glue - 使用 Java 开发工具包的 AWS Glue 作业状态
- python - 如何“非规范化”一个 pytorch 张量?
- .net - Salesforce API 客户端
- javascript - How can a modal reopen another modal? (Angular 4+)
- php - how to split string by first new line
- javascript - ES2015 string iterator information about index