简体   繁体   English

如何仅在 ASP.NET Core 中禁用缓存以进行开发?

[英]How to disable cache for development only in ASP.NET Core?

I want to disable caching when running ASP.NET core application in Development environment.我想在开发环境中运行 ASP.NET 核心应用程序时禁用缓存。 How can i do that?我怎样才能做到这一点?

I'm setting cache up in Startup:我在启动中设置缓存:

services.AddMemoryCache();

I want to disable cache in templates, which use the <cache> tag:我想在使用<cache>标签的模板中禁用缓存:

<cache expires-after="@TimeSpan.FromSeconds(3600)">

You can simply inject IHostingEnvironment into the startup constructor of your Startup.cs您可以简单地将IHostingEnvironment注入Startup.cs的启动构造函数中

Like So像这样

      private readonly IHostingEnvironment _environment;

       public Startup(IConfiguration configuration,IHostingEnvironment environment)
       {
        _environment = environment;
        Configuration = configuration;
       }

Then you can use the private IHostingEnvironment inside your configures services method .然后,您可以在配置服务方法中使用私有IHostingEnvironment

public void ConfigureServices(IServiceCollection services) 
{
 if(!_environment.IsDevelopment())
    services.AddMemoryCache();
}

EDIT :编辑 :

After rereading the question the cache tags should be disabled aswell.重新阅读问题后,缓存标签也应该被禁用。 I would suggest adding a flag inside your appsettings.devlopment.json called "PageCachingEnabled": "false" .我建议在您的appsettings.devlopment.json添加一个名为"PageCachingEnabled": "false"的标志。

On the view I would then inject the configuration like so在视图上,我会像这样注入配置

@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration
<cache enabled=@Boolean.Parse(Configuration["PageCachingEnabled"]) expires-after="@TimeSpan.FromSeconds(3600)">

The trick is to use services.AddDistributedMemoryCache();诀窍是使用services.AddDistributedMemoryCache(); in development, this will use the memory of the running system as a cache.在开发中,这将使用运行系统的内存作为缓存。

if(Env.IsDevelopment()) {
  services.AddDistributedMemoryCache();
} else {
  services.AddStackExchangeRedisCache();
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM