簡體   English   中英

ASP.NET Core 2.1-內存緩存-控制器無法訪問中間件中設置的值

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

我在Asp.Net Core 2.1 Webapi項目中使用IMemoryCache臨時存儲從RabbitMq通道接收的一些數據。 我在定制的中間件中有一個頻道監聽器。 但是,當我嘗試從控制器訪問緩存中的數據時,其中沒有數據。 我正在使用Autofac作為我的DI框架。

如果將值設置為控制器中的內存緩存,則可以從其他類中獲取該值,例如與此控制器關聯的服務(也在Autofac DI中注冊)。

我的實現如下:

  1. 在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);
    }
  1. 在中間件中,我有

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

messageBody來自RabbitMq的位置

  1. 在控制器中我有

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM