gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 14:47:10 25 4
gpt4 key购买 nike

我正在按照给定的步骤进行操作 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com