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