Session["TSNPAC"] = "TSNPAC";
据我所知,我们可以在控制器之间共享会话值,关于会话为空,可能问题与会话过期时间和asp.net核心中会话的使用有关。
要在 asp.net Core 中使用 session,Startup 必须包含:
Startup.cs 如下:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(20); // set the session expired time.
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
services.AddControllersWithViews();
}
// 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.UseAuthorization();
app.UseSession();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
通过上述配置,我们将会话过期时间设置为20分钟。
然后,在控制器中,我们可以使用以下代码来获取或设置会话中的值:
public const string SessionKeyName = "_Name";
public IActionResult Index()
{
//Requires: using Microsoft.AspNetCore.Http;
if (string.IsNullOrEmpty(HttpContext.Session.GetString(SessionKeyName)))
{
//set value to session
HttpContext.Session.SetString(SessionKeyName, "The Doctor");
}
//Get value from session
var name = HttpContext.Session.GetString(SessionKeyName);
//used to display value in the view page.
ViewData["name"] = name;
return View();
}
如果你想使用 session 来存储对象,你必须添加 SessionExtensions,检查this article。
更多使用session的详细信息,请查看Session State。
如果还是无法通过session获取值,可以考虑将值存入缓存或数据库中。