ASP.NET 核心会话启动问题
ASP.NET core Session startup issues
我一定是遗漏了一些愚蠢的东西..
我正在尝试在我的网络应用程序中使用会话,每当我尝试 运行 该网站时,它都会给我这个:
InvalidOperationException:尝试激活 'EcommerceWebsite.Controllers.HomeController'.
时无法解析类型 'Microsoft.AspNetCore.Http.ISession' 的服务
这是我的创业公司:
public void ConfigureServices(IServiceCollection services)
{
// MVC Shit
services.AddControllers(options => options.EnableEndpointRouting = false);
// DBContext shit
services.AddDbContextPool<ventsus7_InventoryContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddScoped<IIMS, IMSSQL>();
services.AddDbContext<EcommerceWebsiteContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
// Identity shit
services.AddIdentity<EcommerceWebsiteUser, IdentityRole>(config =>
{
config.SignIn.RequireConfirmedEmail = true;
})
.AddDefaultUI()
.AddEntityFrameworkStores<EcommerceWebsiteContext>().AddDefaultTokenProviders();
services.AddAuthentication();
services.AddAuthorization();
// Cache
services.AddMemoryCache();
services.ConfigureApplicationCookie(options =>
{
options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
options.SlidingExpiration = true;
options.LoginPath = "/Identity/Account/Login";
});
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromDays(10);
options.Cookie.IsEssential = true;
});
// Payments Stuff
StripeConfiguration.ApiKey = Configuration.GetSection("Stripe")["SecretKey"];
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
//app.UseHttpsRedirection();
app.UseStaticFiles();
//app.UseRouting();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseAuthorization();
app.UseSession();
app.UseMvc(routes =>
{
routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");
});
}
这是我的控制器:
private readonly ILogger<HomeController> _logger;
private ventsus7_InventoryContext context;
private readonly UserManager<EcommerceWebsiteUser> userManager;
private ISession memorySession;
private JsonSerializerSettings settings = new JsonSerializerSettings()
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
};
public HomeController(ILogger<HomeController> logger, ventsus7_InventoryContext dbContext, UserManager<EcommerceWebsiteUser> userManager, ISession memorySession)
{
_logger = logger;
context = dbContext;
this.userManager = userManager;
this.memorySession = memorySession;
}
使用AddSession和ISession的最佳实践,可以参考下面的代码
家庭控制器:
private readonly ILogger<HomeController> _logger;
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly ISession _memorySession;
public HomeController(ILogger<HomeController> logger, IHttpContextAccessor accessor)
{
_logger = logger;
_httpContextAccessor = accessor;
_memorySession = _httpContextAccessor.HttpContext.Session;
}
public string Set(string key)
{
_memorySession.SetString("key", key);
return "success";
}
public string Get()
{
return _memorySession.GetString("key");
}
Startup.cs
...
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromDays(10);
options.Cookie.IsEssential = true;
});
测试结果
我一定是遗漏了一些愚蠢的东西..
我正在尝试在我的网络应用程序中使用会话,每当我尝试 运行 该网站时,它都会给我这个:
InvalidOperationException:尝试激活 'EcommerceWebsite.Controllers.HomeController'.
时无法解析类型 'Microsoft.AspNetCore.Http.ISession' 的服务这是我的创业公司:
public void ConfigureServices(IServiceCollection services)
{
// MVC Shit
services.AddControllers(options => options.EnableEndpointRouting = false);
// DBContext shit
services.AddDbContextPool<ventsus7_InventoryContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddScoped<IIMS, IMSSQL>();
services.AddDbContext<EcommerceWebsiteContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
// Identity shit
services.AddIdentity<EcommerceWebsiteUser, IdentityRole>(config =>
{
config.SignIn.RequireConfirmedEmail = true;
})
.AddDefaultUI()
.AddEntityFrameworkStores<EcommerceWebsiteContext>().AddDefaultTokenProviders();
services.AddAuthentication();
services.AddAuthorization();
// Cache
services.AddMemoryCache();
services.ConfigureApplicationCookie(options =>
{
options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
options.SlidingExpiration = true;
options.LoginPath = "/Identity/Account/Login";
});
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromDays(10);
options.Cookie.IsEssential = true;
});
// Payments Stuff
StripeConfiguration.ApiKey = Configuration.GetSection("Stripe")["SecretKey"];
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
//app.UseHttpsRedirection();
app.UseStaticFiles();
//app.UseRouting();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseAuthorization();
app.UseSession();
app.UseMvc(routes =>
{
routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");
});
}
这是我的控制器:
private readonly ILogger<HomeController> _logger;
private ventsus7_InventoryContext context;
private readonly UserManager<EcommerceWebsiteUser> userManager;
private ISession memorySession;
private JsonSerializerSettings settings = new JsonSerializerSettings()
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
};
public HomeController(ILogger<HomeController> logger, ventsus7_InventoryContext dbContext, UserManager<EcommerceWebsiteUser> userManager, ISession memorySession)
{
_logger = logger;
context = dbContext;
this.userManager = userManager;
this.memorySession = memorySession;
}
使用AddSession和ISession的最佳实践,可以参考下面的代码
家庭控制器:
private readonly ILogger<HomeController> _logger;
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly ISession _memorySession;
public HomeController(ILogger<HomeController> logger, IHttpContextAccessor accessor)
{
_logger = logger;
_httpContextAccessor = accessor;
_memorySession = _httpContextAccessor.HttpContext.Session;
}
public string Set(string key)
{
_memorySession.SetString("key", key);
return "success";
}
public string Get()
{
return _memorySession.GetString("key");
}
Startup.cs
...
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromDays(10);
options.Cookie.IsEssential = true;
});
测试结果