简体   繁体   English

ASP.NET Core 2.1-内存缓存-控制器无法访问中间件中设置的值

[英]ASP.NET Core 2.1 - Memory cache - value set in middleware cannot be accessed by controller

I am using IMemoryCache in Asp.Net Core 2.1 Webapi project to temporarily store some data received from RabbitMq channel. 我在Asp.Net Core 2.1 Webapi项目中使用IMemoryCache临时存储从RabbitMq通道接收的一些数据。 I have a channel listener in a customised middleware. 我在定制的中间件中有一个频道监听器。 But when I try to access the data in the cache from controller, there is no data in it. 但是,当我尝试从控制器访问缓存中的数据时,其中没有数据。 I am using Autofac as my DI framework. 我正在使用Autofac作为我的DI框架。

If I set a value to memory cache in a controller, I can get it from other classes, such as a service (also registered in Autofac DI) associated with this controller. 如果将值设置为控制器中的内存缓存,则可以从其他类中获取该值,例如与此控制器关联的服务(也在Autofac DI中注册)。

My implementation is as follow: 我的实现如下:

  1. In Startup.cs, I have 在Startup.cs中,我有

services.AddMemoryCache();

and then use the middleware as 然后使用中间件作为

app.UseMiddleware<RabbitMqConsumerMiddleware>();
app.UseCors("default")
    .UseAuthentication()
    .UseMvc();`

My Autofac registration is as follow: 我的Autofac注册如下:

Here is my Autofac registration 这是我的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);
    }
  1. In the middleware, I have 在中间件中,我有

     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); } 

where messageBody comes from RabbitMq messageBody来自RabbitMq的位置

  1. In controller I have 在控制器中我有

     [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(); } } 

But _memoryCache is always empty. 但是_memoryCache始终为空。

I put a breakpoint in my middleware and confirm that data has been set to the cache. 我在中间件中放置了一个断点,并确认已将数据设置为缓存。

Do I use memory cache in a wrong way? 我是否以错误的方式使用内存缓存? Thanks 谢谢

Without knowing your full configuration, I guess one issue could be that you have registered the new middleware after the Mvc middleware. 不知道您的完整配置,我想一个问题可能是您在Mvc中间件之后注册了新的中间件。
Your registration should look like this: 您的注册应如下所示:

app.UseMiddleware<RabbitMqConsumerMiddleware>();
app.UseMvc();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Asp.Net Core:在控制器外使用内存缓存 - Asp.Net Core: Use memory cache outside controller 将模型值设置为小写的 ASP.NET Core 2.1 属性 - ASP.NET Core 2.1 Attribute to set model value to lowercase ASP.Net Core 2.1中间件WindowsPrincipal ClaimsPrincipal - ASP.Net Core 2.1 Middleware WindowsPrincipal ClaimsPrincipal SqlException:当 IDENTITY_INSERT 设置为 OFF ASP.NET Core 2.1 时,无法在表“类别”中插入标识列的显式值 - SqlException: Cannot insert explicit value for identity column in table 'Categories' when IDENTITY_INSERT is set to OFF ASP.NET Core 2.1 asp.net 内核中的中间件仅在清除缓存的情况下工作 - Middleware in asp.net core work only with clear cache 承载令牌身份验证-如何在控制器ASP.NET Core 2.1中获取登录用户值 - Bearer Token Auth - How to get SignIn User Value in controller ASP.NET Core 2.1 从asp.net core 2.1中的控制器访问BackgroundService - access BackgroundService from controller in asp.net core 2.1 控制器ASP.net Core 2.1中的Jwt角色身份验证 - Jwt Role authentication in controller ASP.net core 2.1 ASP.NET Core 2.1 Razor 表单,发布未到达控制器 - ASP.NET Core 2.1 Razor Form, Post not reaching Controller Asp.net核心:中间件到控制器转换问题? - Asp.net Core: middleware to controller conversion issue?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM