c# - ASP.NET Core 2.1 - 实现 MemoryCache 时出错

标签 c# asp.net caching asp.net-core

我正在按照给定的步骤进行操作 hereASP.NET Core 中实现 MemoryCache 并且当我启动应用程序时(dotnet run 从命令提示符),我收到以下错误。

System.InvalidOperationException: Unable to resolve service for type 'Microsoft.Extensions.Caching.Distributed.IDistributedCache' while attempting to activate 'Microsoft.AspNetCore.Session.DistributedSessionStore'.

令我困惑的是,我正在使用 services.AddMemoryCache()NOT services.AddDistributedMemoryCache()。此 bin 中提供了完整的堆栈跟踪. 我只引用了这些包

<PackageReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.1.2" PrivateAssets="All" />
<PackageReference Include="System.Configuration.ConfigurationManager" Version="4.5.0" />

我的配置

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseStaticFiles();
    app.UseSpaStaticFiles();
    app.UseSession();
    app.UseCors(
        builder => builder
            .WithOrigins("http://localhost:4200")
            .AllowAnyHeader()
            .AllowAnyMethod()
            .AllowAnyOrigin()
            .AllowCredentials());
    app.UseMvc(
        routes =>
        {
            routes.MapRoute(
                "default",
                "api/{controller}/{action}/{id?}");
        });
}

配置服务

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors();
    services
        .AddMvcCore()
        .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
        .AddJsonFormatters();

    services.AddMemoryCache();

    // Angular files will be served from this directory
    services.AddSpaStaticFiles(configuration => { configuration.RootPath = "wwwroot"; });
    services.AddSession(
        options =>
        {
            // Set a short timeout for easy testing.
            options.IdleTimeout = TimeSpan.FromHours(1);
            options.Cookie.HttpOnly = true;
        });
}

程序.cs

  public static IWebHostBuilder CreateWebHostBuilder(string[] args)
    {
        return WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>();
    }

    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }

最佳答案

services.AddControllers() 之后简单地添加 services.AddMemoryCache() 对我有用。

关于c# - ASP.NET Core 2.1 - 实现 MemoryCache 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53624779/

相关文章:

c# - 在 GridView 控件中访问 Boundfield

使用 SQL_CACHE 和 SQL_NO_CACHE 的 MySQL 最佳实践

php - 如何缓存 php soapclient 响应?

c# - 使用 xsd :id in C# web service

c# - 双线性插值 - DirectX 与 GDI+

c# - 在哪里可以找到 Win32 常量?

php - 如何防止浏览器图片缓存?

c# - Ajax.beginform 执行完整回发而不是部分回发

c# - 如何检索给定 HttpRequestMessage 的路由模板变量?

c# - 是否可以在不购买 Visual Studio 许可证的情况下使用团队资源管理器进行版本控制?