为什么会话在Net Core项目中不起作用?

时间:2019-04-05 14:05:38

标签: c# asp.net-mvc session asp.net-core .net-core

我正在尝试在我的项目中添加一个会话。我添加了所有定义和参考。设置会话时,该会话具有一个值。但是在另一个操作中,会话似乎为空

我将此配置添加到Startup.cs:

namespace LDI.Web
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
             Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
                     {
                          options.CheckConsentNeeded = context => true;
                          options.MinimumSameSitePolicy = SameSiteMode.None;
                     });
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddDistributedMemoryCache();
            services.AddSession(options => {
                          options.IdleTimeout = TimeSpan.FromMinutes(30);
                          options.Cookie.HttpOnly = true;
                          options.Cookie.IsEssential = true;
                     });
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();
            app.UseSession();

            app.UseMvc(routes =>
                {
                    routes.MapRoute(
                           name: "default",
                           template: "{controller=Home}/{action=Index}/{id?}");
                });
        }
    }
}

我正在使用NetCore 2.1,并且已经实现了Microsoft.AspNetCore.Session依赖性。

HomeController.cs

[HttpPost]
public IActionResult Login(User user)
{
    Context db = new Context();
    UserRepo repo = new UserRepo(db);

    Expression<Func<User,bool >> filter = x => x.Username==user.Username && x.Password==user.Password;
    User currentUser = repo.Get(filter);

    if (currentUser != null)
    {
        HttpContext.Session.SetInt32("UserID", currentUser.ID);
        int? id = HttpContext.Session.GetInt32("UserID");

        //id has value
        return RedirectToAction("Index");
    }

    return View();
}

public IActionResult Index()
{
    repo = new UserRepo(db);
    int? id = HttpContext.Session.GetInt32("UserID");
    //id has no value

    Expression<Func<User, bool>> filter = x => x.ID == id;
    User user = repo.Get(filter);
    ViewBag.User = user;

    return View();
}

在“登录操作”中,Id有一个值,但在“索引操作”会话中为null,而id没有任何值。

0 个答案:

没有答案